Laravel

Laravel 模型关系:多对多

配套视频地址:https://www.bilibili.com/video/av73028135?p=4


多对多:一个人可以扮演多个角色,一个角色可以被多个人扮演。


数据结构

# users: id, name
# roles: id, title
# role_user: id, role_id, user_id

模型配置

// App\Role
public function users(){
    return $this->belongsToMany('App\User');
}
// App\User
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]);

定制模型

指定模型关系中的中间表名称,例如指定中间表名称为 rid_uid
// App\User
public function roles(){
    return $this->belongsToMany('App\Role', 'rid_uid');
}

// App\Role
public function users(){
    return $this->belongsToMany('App\User', 'rid_uid');
}
指定中间表中外键字段名称
// App\User
public function roles(){
    return $this->belongsToMany('App\Role', 'role_user', 'uid', 'rid');
}

// App\Role
public function users(){
    return $this->belongsToMany('App\User', 'role_user', 'rid', 'uid');
}
取出中间表字段
$user = App\User::find(1);

foreach ($user->roles as $role) {
    echo $role->pivot->role_id;
}
重命名 pivot
return $this->belongsToMany('App\Role')->as('subscription');

在 pivot 中添加 created_at, updated_at

return $this->belongsToMany('App\Role')->withTimestamps();
在 pivot 中添加其他字段
return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');
模型关系中设置筛选条件
return $this->belongsToMany('App\Role')->wherePivot('approved', 1);

return $this->belongsToMany('App\Role')->wherePivotIn('priority', [1, 2]);

发表评论