业务场景#

– 用户对应多个角色

– 角色也可以被其他用户所拥有

表设计#

users
    id
    name
roles
    id
    name
role_user
    id
    role_id
    user_idCopy

模型类#

<?php

namespace App\Models;

class Role extends AbstractModel
{
    protected $table = 'roles';

    public function users()
    {
        return $this->belongsToMany(User::class,'role_user', 'role_id', 'user_id')
            ->using(RoleUser::class)
            ->withPivot('id', 'created_at','updated_at')
            ->withTimestamps();
    }

    public function roleUser()
    {
        return $this->hasMany(RoleUser::class,'role_id')->orderBy('id', 'desc');
    }
}
<?php

namespace App\Models;

class User extends Authenticatable
{

    protected $table = 'users';

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id')
            ->withTimestamps();
    }

}

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\Pivot;

class RoleUser extends Pivot
{
    protected $table = 'role_user';

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function role()
    {
        return $this->belongsTo(Role::class, 'role_id');
    }
}
Copy

使用方法#

## 创建用户和角色之间的关联
$user->roles()->attach([
  $role1->id,
  $role2->id,
]);
## 或者用sync()函数防止重复关联
$user->roles()->sync([
 $role1->id,
 $role2->id,
]);
## 创建角色和用户之间的关联
$role->users()->attach([
   $user1->id,
   $user2->id,
]);
## 或者用sync()函数防止重复关联
$role->users()->sync([
   $user1->id,
   $user2->id,
]);

## 查询记录
$user->roles;
$role->users;

## 删除记录
// 删除用户的一个角色
$user->roles()->detach($role->id);
// 删除角色的一个用户
$role->users()->detach($user->id);
// 删除用户的所有角色
$user->roles()->detach();
// 删除角色的所有用户
$role->users()->detach();
Copy
http://www.gtalent.cn/exam/interview?token=82b4221a5f125aa02db3e7f546e30ee1