多对多关联中,附加关联的同时更新关联中间表的字段无效
用户表、班级表、班级成员关联表如下
users
id - integer
name - string
iclasses
id - integer
name - string
iclass_user
user_id - integer
iclass_id - integer
is_teacher - integer
User模型
public function iclasses()
{
return $this->belongsToMany(Iclass::class)->withPivot('is_teacher')->withTimestamps();
}
Iclass模型
public function users(){
return $this->belongsToMany(User::class)->withPivot('is_teacher')->withTimestamps();
}
public function students(){
return $this->belongsToMany(User::class)->wherePivotNull('is_teacher')->withPivot('is_teacher')->withTimestamps();
}
public function teachers(){
return $this->belongsToMany(User::class)->wherePivotNotNull('is_teacher')->withPivot('is_teacher')->withTimestamps();
}
表单提交
以下为Dcat Admin数据表单片段代码,参数释义参照:事件以及表单响应《Dcat Admin 中文文档》
$form->saved(function (Form $form, $result){
if ($result && !empty($form->input('iclasses'))){
$iclass_ids = explode(",", $form->input('iclasses'));
$relations = [];
foreach ($iclass_ids as $iclass_id){
$relations[$iclass_id] = [
'is_teacher' => 1
];
}
$form->model()->iclasses()->attach($relations);
//$form->model()->iclasses()->sync($relations); //同样无效
}
});
以上代码,中间关联关系表数据插入正常,唯独is_teacher
字段写不进去值。
初步学习Laravel,文档理解的不够深刻,还在持续学习中,请各路大仙指点,不胜感激!
正在努力学习的小逗比 [ dobeen.net ]
改为:
正常!