Get the data from 2 tables using polymorphic relationships
I am writing this question because I have been trying for hours to find a solution to my problem and I have not succeeded. It happens that I am trying to return in a method that I have created within my model, the content of the relations of 2 tables that contain records associated with a certain one. What happens is that one of those tables has a many-to-many polymorphine relationship and the other is a many-to-many relationship. I show you the structure of what I have created so far:
Tables:
1. users
2. roles
3. permissions
4. permission_role (Pivot table for many to many relationship between permissions and roles )
These 2 tables are for the polymorphic relationship, since not only the ```User``` model will be used, but to make the question a little more specific, I have used the name ```user``` in the tables.
5. user_roles
6. user_permissions
- A user can have multiple roles and vice versa.
- A role can have multiple permissions and vice versa.
- A user can directly have multiple permissions (without the user being associated with a role)
I show you the structure of my models:
Relations
Models/Role.php
<?php
namespace App\Models;
...
class Role extends Model
{
...
public function users()
{
return $this->morphedByMany(User::class, 'model', 'user_roles');
}
public function permissions()
{
return $this->belongsToMany(Permission::class);
}
}
Models/Permissions.php
<?php
namespace App\Models;
...
class Permission extends Model
{
...
public function users()
{
return $this->morphedByMany(User::class, 'model', 'user_permissions');
}
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
Models/User.php
<?php
namespace App\Models;
...
class User extends Authenticatable
{
...
public function roles()
{
return $this->morphToMany(Roles::class, 'model', 'user_roles');
}
public function permissions()
{
return $this->morphToMany(Permissions::class, 'model', 'user_permissions');
}
}
What I am trying to achieve is to have in the User model, a method that allows me to obtain all the permissions that the user possesses, either those that it possesses directly and those that it possesses through the roles it has associated with. Suppose the following:
-
User 1is assignedRole 1 -
Role 1, has 2 permissions,Permission 1andPermission 2 -
User 1also hasPermission 3permission directly associated.
Thus, the permissions that User 1 has are: Permission 1, Permission 2 and Permission 3
I have tried to do the following:
Models/User.php
<?php
namespace App\Models;
...
class User extends Authenticatable
{
public function getAllPermissions()
{
return $this->loadMissing('roles', 'permissions')->roles->flatMap(function ($role) {
return $role->permissions;
});
}
...
}
but I don't get the results I expect. I would appreciate in advance any help you can give me.
Please or to participate in this conversation.