17. 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, ['create_at' => now()]);

# 批量添加
$user->roles()->attach([
    1 => ['expires' => $expires],
    2 => ['expires' => $expires],
]);

$user = App\User::find(1);
# 删除关联表内容 user_id = 1 and $orderId
$user->roles()->detach($roleId);
# 删除关联表内容 user_id = 1
$user->roles()->detach();

# 无论多少角色都变成1。2。3。删除 角色 1。2。3之外的
$user->roles()->sync([1, 2, 3]);
# 更新1字段内容
$user->roles()->sync([1 => ['expires' => true], 2, 3]);
# 
$user->roles()->syncWithoutDetaching([1, 2, 3]);
# role有1就删除 没有就添加
$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]);

posted on   何苦->  阅读(54)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示