请问多对多模型关联,怎么在保存时,给中间表附加字段设定默认值?
这是个自关联的多对多情况:表A中的记录相互之间有不同类别的排斥;
现在中间表中有一个额外的type
字段,我怎么才能在保存时给中间表的这个type
字段设置默认值?
public function A1()
{
return $this->belongsToMany(A::class, 'relation_table', 'main_id', 'secondary_id')->withPivot('type')->wherePivot('type', 1);
}
public function A2()
{
return $this->belongsToMany(A::class, 'relation_table', 'main_id', 'secondary_id')->withPivot('type')->wherePivot('type', 2);
}
// 我怎么在save的时候将这个对应的A1和A2的type值给设置上去? 我尝试使用attach方法,不过没有起到作用 - -!
public function save () {
return parent::save();
}
非常感谢~~
在中间表上保存额外数据
当处理多对多关联时,save 方法还可以使用第二个参数,它是一个属性数组,包含插入到中间表的额外字段数据。
App\User::find(1)->roles()->save($role, ['expires' => $expires]);
文档里有