Laravel复选框具有多对多关系

时间:2017-05-01 18:39:55

标签: php laravel checkbox blade laravelcollective

我正在从DB中提取疾病并在前端显示复选框:

<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递增

1 个答案:

答案 0 :(得分:1)

这里的问题是sync方法不应该是关联数组。您应该将一个包含要附加的疾病ID的数组传递给它。为此,您需要预处理阵列:

if ($request->has('diseases')) {
    $diseases = array_keys(array_filter($request->diseases)));
    $patient->diseases()->sync($diseases);
}

如果$request->diseases返回Laravel Collection,您可能需要先调用toArray()或将其强制转换为数组。

参考:https://laravel.com/docs/5.4/eloquent-relationships#inserting-and-updating-related-models

的“同步关联”部分