1

I have three Models User, Role and Permission. There is complicated but well-known relation between these Models and their tables.

Tables and their columns :

users roles permissions permission_role
id id id id
... ... ... role_id
role_id ... ... permission_id

So each User has only one role and every role has many permissions.

<?php

class User
{


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

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


class Role
{


public function users()
{
    return $this->hasMany(User::class);
  
}

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


class Permission
{


public function roles()
{
    return $this->belongsToMany(Role::class);
    
}

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

I can access

  1. $user->role,
  2. $user->role->permissions,
  3. $role->users,
  4. $role->permissions
  5. $permission->roles

except for

  1. $permission->users

which returns sql error :

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.permission_id' in 'field list' (SQL: select `users`.*, `roles`.`permission_id` as `laravel_through_key` from `users` inner join `roles` on `roles`.`id` = `users`.`role_id` where `roles`.`permission_id` = 1) 

But why?

Artin GH
  • 546
  • 2
  • 10
  • 21

1 Answers1

0

Can you try like this:

Permission
public function users()
{
    return $this->hasManyThrough(
        User::class,    // The model to access to
        PermissionRole::class,    // The intermediate table that connects the User with the Role.
        'permission_id',   // The column of the intermediate table that connects to this model by its ID.
        'role_id',    // The column of the intermediate table that connects the Role by its ID.
        'id',    // The column that connects this model with the intermediate model table.
        'role_id'   // The column of the Users table that ties it to the Roles. 
    );
}

I found this article.

And if you compare with your tables it can be like:

  • audio_files table is your users
  • podcast table is your roles
  • subscription table is your permission_role
  • users table is your permissions

Maybe it's confusing, but please let me know if this works.

mare96
  • 3,749
  • 1
  • 16
  • 28