简体   繁体   中英

How to establish a hasManyThrough relationship in laravel for roles and permissions?

So I understand how to load the roles for a user and the permissions for a role.

But now I have a user table, a role table, and a permission table. I also have role_user table for linking users and roles. And of course a permission_role for linking permissions and roles.

Now when I want to get all the roles for the user, I simply do something like this:

public function roles()
{
        return $this->belongsToMany('Uppdragshuset\AO\Tenant\Models\Role');
}

Similarly I can fetch permissions for roles like so:

public function permissions()
{
        return $this->belongsToMany(Permission::class);
}

Now according to the documentation on laravel, I can directly fetch permissions for a user by using the hasManyThrough relation too like so:

public function permissions()
{
    return $this->hasManyThrough(Permission::class, Role::class);
}

But this is returning with an error saying:

Unknown column 'role.user_id' in 'field list'

I think I understand why. Laravel is looking for user_id field in the role table but it does not understand that it is a many to many relation and it should look for it in the pivot table.

So what is the way around this? Is there a way around this in Eloquent or will I have to resort to using the query builder? And if yes, how to do the same thing with the query builder?

HasManyThrough can only be used to connect two HasMany relationships. There is no native relationship for your case.

I created a HasManyThrough relationship with unlimited levels and support for BelongsToMany :
Repository on GitHub

After the installation, you can use it like this:

class User extends Model {
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function permissions() {
        return $this->hasManyDeep(Permission::class, ['role_user', Role::class, 'permission_role']);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM