我有一个多对多关系,其中我有两个属于ToMany的模型。
所以我想更新数据透视表,但首先我想知道该数据透视表上是否已经存在两个模型。
这是下面两个模型中我的关系的定义:
AnalysisRequest模型
public function request_methods()
{
return $this->belongsToMany('App\Models\Methodologies')->withTimestamps();;
}
和其他模型:方法论模型
public function methods_requested()
{
return $this->belongsToMany('App\Models\AnalysisRequest')->withTimestamps();;
}
因此,这两个模型都有自己的数据透视表,并附加了所有 ID 。现在我想发生的是,当两个模型之间都存在现有的附加模型时,我希望在无法实现的视图上选中该复选框。
这是数据透视模型
<?php
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
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',
];
}
这是下面的我的代码 controller :
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>
此处question的引用可能与我的问题有关。
我的视图中出现错误,原因是:
违反完整性约束:1052字段列表中的列“ id”为 模棱两可(SQL:从
id
内部联接中选择methodologies
analysis_request_methodologies
上的methodologies
。id
=analysis_request_methodologies
。methodologies_id
其中analysis_request_methodologies
。analysis_request_id
= 10)
在referenced question中,该解决方案表示我需要使用lists
,但是在 Laravel 5 中它已贬值,我需要改用pluck
。但是仍然无法解决难题。
感谢有人可以帮助您。 预先感谢。
答案 0 :(得分:2)
我假设您的相关表名称为methodologies
,因此您的查询应如下所示
$checkeds = AnalysisRequest::find($id)->request_methods()->pluck('methodologies.id');
您必须指定表名,因为当您说request_methods()
mysql应该知道ID属于哪个表时,就雄辩地创建查询并联接表