php - Get total permissions from users & roles belongsToMany
问题描述
I have 3 models:
- User
- Role
- Permission
Note:
- a user can have direct permissions
- a role can have permissions
- a user can have roles
I'm trying to get the total permissions a user has, either through their direct permissions or through their roles permissions. So I need to combine both into 1 collection and count the total.
I've set up the belongsToMany relationships for User
and Role
:
public function permissions()
{
return $this->belongsToMany('App\Permission');
}
How do I do this?
解决方案
You need to use the hasManyThrough
relation
Here is the link to the documentation: Eloquent Documentation
so you would do something like this:
public function permissions()
{
$directPermissions = $this->belongsToMany('App\Permission');
$rolePermissions = $this->hasManyThrough('App\Permissions', 'App\Role');
return $directPermissions->merge($rolePermissions);
}
推荐阅读
- c++ - 为什么我的 BaseClass:Method 代码编译(带有单冒号)?
- nlp - Spacy:自动在文本中查找引理模式
- c# - 在 .NET Core 类构造函数中注入接口的所有实现者
- python - 输入列表 Python 的列表(例如 input() [[1,2,3],[4,5,6]])
- kubernetes - 在 Kubernetes 集群上使用 Jmeter GUI 运行 Perf 测试
- google-cloud-platform - GCP Identity Aware Proxy 无法识别我创建的允许访问 ip 范围“35.235.240.0/20”的防火墙规则
- vb.net - 如何使用 Object 类型变量访问类的属性?
- javascript - 在 Rails 6 中运行 easyAutocomplete 时出错 - easyAutocomplete 不是函数
- c++ - Node* p 和 Node * p 有什么区别?
- python - 将范围索引转换为日期时间索引时出错