我正在从数据库中提取疾病并在前端使用复选框呈现它们:
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
@foreach($diseases as $disease)
<div class="col-md-6">
<div class="form-group">
<label>{{ Form::checkbox('diseases','0','',
['class' => 'grey','data-id'=> $disease->id]) }}
{{$disease->title}}
</label>
<div class="clearfix"></div>
</div>
</div>
@endforeach
</div>
提交表单后,我得到如下结果$request->diseases
:
1:"1"
2:"1"
3:"0"
4:"1"
5:"0"
6:"0"
...
其中第一个数字表示disease_id
,另一个表示复选框是否被选中。与数据透视表的关系在模型中正确建立,我在控制器中尝试做的是:
if ($request->has('diseases')) {
$patient->diseases()->sync($request->diseases);
}
但这失败并出现错误:
Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key
constraint fails (`db_name`.`disease_patient`, CONSTRAINT `disease_patient_patient_id_foreign`
FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`) ON DELETE CASCADE) (SQL: insert into
`disease_patient` (`disease_id`, `patient_id`)
values (17, {"1":"0","2":"0","3":"1","4":"1","5":"1","6":"1","7":"1","8":"1","9":"0","10":"1","11":"0","12":"1","13":"0","14":"0","15":"0","16":"0","17":"0","18":"0","19":"0","20":"0","21":"0","22":"0","23":"0"}))
模型内部关系Patient
:
protected $guarded = ['id'];
public function diseases()
{
return $this->belongsToMany('App\Disease', 'disease_patient', 'disease_id', 'patient_id');
}
编辑:
当我做:
$diseases = array_keys(array_filter(json_decode($request->diseases, true)));
return $diseases;
我得到这样的 ID 列表:
0:1
1:2
2:8
3:14
4:15
5:21
和错误:
(SQL: insert into `disease_patient` (`disease_id`, `patient_id`) values (33, 1))
随着disease_id
每个请求的增加