Laravel 5.5 更新多对多关系模型的复选框



我有一个多对多的关系,我有两个模型,彼此属于ToMany。

所以我想更新数据透视表,但首先我想知道这两个模型是否已经存在于这个数据透视表上。

因此,以下是我在以下两个模型中对关系的定义:

分析请求模型

public function request_methods()
{
return $this->belongsToMany('AppModelsMethodologies')->withTimestamps();;
}

在我的另一个模型中:方法模型

public function methods_requested()
{
return $this->belongsToMany('AppModelsAnalysisRequest')->withTimestamps();;
}

因此,这两个模型都有自己的数据透视表,并附加了所有ID。现在我想发生的是,当两个模型相互附加现有模型时,我希望在我无法实现的视图上选中复选框。

这是枢轴模型

<?php
namespace AppModels;
use Eloquent as Model;
use IlluminateDatabaseEloquentSoftDeletes;
class AnalysisRequestMethodologies extends Model
{
public $table = 'analysis_request_methodologies';
public $fillable = [
'analysis_request_id',
'methodologies_id',
];
/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'analysis_request_id' => 'integer',
'methodologies_id' => 'integer',
];
/**
* Validation rules
*
* @var array
*/
public static $rules = [
'analysis_request_id' => 'required|unique_with:analysis_request_methodologies,methodologies_id',
'methodologies_id' => 'required',
];
}

这是我下面的代码控制器

public function edit($id)
{
$analysis_request = $this->analysisrequestRepository->findWithoutFail($id);
$checkeds = AnalysisRequest::find($id)->request_methods()->pluck('id');
return view('encoder-dashboard.analysis-request-methods.create', compact('analysis_request', 'checkeds'));
}

在我看来

<div class="form-group col-sm-12">
@forelse($analysis_request->category->methodology as $method)
<label>
<?php $checked = in_array($method->id, $checkeds) ? true : false; ?>
{{ Form::checkbox('methodologies_id[]', $method->id) }}
{{ $method->name }} with the lead time of {{ $method->lead_time }} and the DOH standard of {{ $method->doh_standard }}
</label>
@empty
<h3>The category you selected has no method yet</h3>
@endforelse
</div>

有可能与我的问题相关的问题的参考。

有一个错误的观点是:

完整性约束冲突:1052 字段列表中的列"id"为 不明确(SQL:从内部联接中选择idmethodologiesanalysis_request_methodologiesmethodologies.id=analysis_request_methodologies.methodologies_idanalysis_request_methodologies.analysis_request_id= 10(

在引用的问题中,解决方案说我需要使用lists但它在Laravel 5中被折旧了,我需要改用pluck。但仍然无法解决难题。

如果有人可以提供帮助,请不胜感激。 提前谢谢。

我假设您的相关表名是methodologies,因此您的查询应如下所示

$checkeds = AnalysisRequest::find($id)->request_methods()->pluck('methodologies.id');

您必须指定表名,因为当您说 mysql 应该知道 id 属于哪个表时,雄辩地创建查询和连接表request_methods()

最新更新