Laravel 模型关联 多对多
定义
在Model中定义方法,调用belongsToMany
belongsToMany常用参数说明:
| 参数位置 | 参数名 | 定义 |
|---|---|---|
| 1 | $related | 关联模型的类名 |
| 2 | $table | 中间表名 |
| 3 | $foreignPivotKey | 当前模型在中间表里的字段名 |
| 4 | $relatedPivotKey | 关联模型在中间表里的字段名 |
public function posts()
{
return $this->belongsToMany($this, 'wechat_multi_post_post', 'multi_post_id', 'post_id')
->orderBy('wechat_multi_post_post.index')
->withPivot('index');
}
获取中间表字段
利用模型中的pivot属性访问,但是默认只有两个模型的key,如果需要额外的字段需要在定义时用withPivot声明需要的字段名
根据中间表排序
在定义关联的时候可以用orderBy排序
更新中间表数据
-
sync 同步更新中间表
-
根据id更新
$this->posts()->sync($postIds); -
需要更新额外的字段
$this->posts()->sync([1=>['index'=>0], 2=>['index'=>1]]);
-
-
syncWithoutDetaching 只增加不减少
-
toggle 切换
-
更新已存在的记录
//array $attributes $this->posts()->updateExistingPivot($postId, $attributes);

浙公网安备 33010602011771号