1

我正在从数据库中提取疾病并在前端使用复选框呈现它们:

<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每个请求的增加

4

1 回答 1

1

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

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

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

参考: https ://laravel.com/docs/5.4/eloquent-relationships#inserting-and-updating-related-models 的“同步关联”部分

于 2017-05-01T18:56:40.353 回答