多对多:一个人可以扮演多个角色,一个角色可以被多个人扮演。
表结构
# users: id, name
# roles: id, title
# role_user: id, role_id, user_id
模型配置
// App\Role
//第一个参数是关联模型的类名,第二个参数 $table 是建立多对多关联的中间表名
//第三个参数是 $foreignPivotKey 指的是中间表中当前模型类的外键
//第四个参数 $relatedPivotKey 是中间表中当前关联模型类的外键
//第五个参数 $parentKey 表示对应当前模型的哪个字段(
//第六个参数 $parentKey 表示对应当前模型的哪个字段(
//最后一个参数 $relation 表示关联关系名称,
public function users(){
return $this->belongsToMany('App\User');
}
// App\User
//第一个参数是关联模型的类名,第二个参数 $table 是建立多对多关联的中间表名
//第三个参数是 $foreignPivotKey 指的是中间表中当前模型类的外键
//第四个参数 $relatedPivotKey 是中间表中当前关联模型类的外键
//第五个参数 $parentKey 表示对应当前模型的哪个字段(
//第六个参数 $parentKey 表示对应当前模型的哪个字段(
//最后一个参数 $relation 表示关联关系名称,
public function roles(){
return $this->belongsToMany('App\Role');
}
增删改查
增
$user = App\User::find(1);
$user->roles()->attach($roleId);
// $roleId = 1;
// $roleId = [1, 2];
// $roleId = Role::find(1);
$user->roles()->attach($roleId, ['expires' => $expires]);
$user->roles()->attach([
1 => ['expires' => $expires],
2 => ['expires' => $expires],
]);
删
$user->roles()->detach($roleId);
$user->roles()->detach();
改
$user->roles()->sync([1, 2, 3]);
$user->roles()->sync([1 => ['expires' => true], 2, 3]);
$user->roles()->syncWithoutDetaching([1, 2, 3]);
$user->roles()->toggle([1, 2, 3]);
// 更新中间表记录
$user = App\User::find(1);
$user->roles()->updateExistingPivot($roleId, $attributes);
查
$role = User::find(1);
$role->users;
Role::with('users')->find([1, 2]);