多对多关联中,附加关联的同时更新关联中间表的字段无效

用户表、班级表、班级成员关联表如下

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 ]
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
Mutoulee
最佳答案
$form->model()->iclasses()->attach($relations);

改为:

$user = User::find($result);
$user->iclasses()->attach($relations);

正常!

2年前 评论
讨论数量: 7
Mutoulee

:cry: 大佬都喝下午茶去了么?

2年前 评论

中间表模型iclass_user fillable加了吗

2年前 评论
Mutoulee

@biiiiiigmonster 感谢回复! 中间表没有模型。

2年前 评论
Mutoulee

问题还是没有搞清楚,继续求教。

2年前 评论

附加数据需要额外写,$form->model()->iclasses()->attach($relations,['is_teacher' => 1]);

2年前 评论
Mutoulee

@wozaihanni 感谢回复。 按照您的这种方法,代码就是:

foreach ($iclass_ids as $iclass_id){
    $form->model()->iclasses()->attach($iclass_id, ['is_teacher' => 1]);
}

这种方法我也试过了,一样的写不进去。

您这种传参是更新一个关联关系,第一个参数是关联外键,第二个参数是更新的中间表字段。 文档中也说了可以传键值数组,key即为关联外键,value是要附带更新的数组。

2年前 评论
Mutoulee
$form->model()->iclasses()->attach($relations);

改为:

$user = User::find($result);
$user->iclasses()->attach($relations);

正常!

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!