gpt4 book ai didi

mysql - Laravel Eloquent - 从关系中检索数据

转载 作者:行者123 更新时间:2023-11-29 15:43:29 24 4
gpt4 key购买 nike

我需要帮助才能从数据库中的用户、角色和权限之间的关系获取数据。请看下面...

数据库:

用户

id    name   role_id
1 Phil 1
2 Rob 1
3 Dave 2

用户角色

id    name
1 Admin
2 Staff

权限

id    endpoint
1 /users
2 /roles

用户角色权限

user_role_id     permissions_id
1 1
1 2
1 2

从用户模型中,我希望能够从权限表中获取数据,这样我就知道用户拥有什么访问权限。

这是模型:

用户.php

class User extends Model implements AuthenticatableContract, AuthorizableContract
{
use Authenticatable, Authorizable, SoftDeletes;

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'role_id'
];

/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'password',
];

protected $dates = [
'deleted_at'
];

public function role()
{
return $this->belongsTo('App\User');
}

public permissions()
{
?????
}

}

用户角色.php

class UserRole extends Model {

protected $fillable = ['name'];

protected $hidden = [];

public function users()
{
return $this->hasMany('App\User');
}

public function permissions()
{
return $this->belongsToMany('App\Permission', 'user_role_permissions');
}

}

权限.php

class Permission extends Model {

protected $fillable = ['endpoint'];

protected $hidden = [];

public function roles()
{
return $this->belongsToMany('App\UserRoles','user_role_permissions');
}

}

请帮忙!

最佳答案

您已正确定义了所有必需的关系。您可以像这样使用它:

User::with('role.permissions')->first();
// It gives you all the permissions that are assigned to the role assigned to the underlying user :)
// Pretty vague to explain though

您不需要在 User 模型上定义 permission()

关于mysql - Laravel Eloquent - 从关系中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57332046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com