首页 > 解决方案 > Get total permissions from users & roles belongsToMany

问题描述

I have 3 models:

Note:

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?

标签: phplaraveleloquentrelationship

解决方案


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);
}

推荐阅读