mardi 4 décembre 2018

Transform Raw Union Query into Eloquent Relationship

i've a question about Laravel Relationships.

I've a raw union query and i want to translate into a eloquent relationship.

First of all... i have 4 tables involved:

roles

id|name

permissions

id|name|code|description

permission_role

role_id|permission_id

users

id|...........|role_id

permission_user

user_id|permission_id

Inside my User model, i've this method:

/**
 * @TODO: Transform this into a eloquent relationship
 * 
 * @return Collection
 */
public function permissions()
{
    $query = sprintf('
        (
            SELECT permissions.*
            FROM permissions
            INNER JOIN permission_role ON permission_role.permission_id = permissions.id
            WHERE permission_role.role_id = %s
        ) UNION
        (
            SELECT permissions.*
            FROM permissions
            INNER JOIN permission_user ON permission_user.permission_id = permissions.id
            WHERE permission_user.user_id = %s
        )', $this->role_id, $this->id);

    return Permission::hydrate(DB::select($query));
}

The point is, i want to fetch all permissions by the role that the user is associated, and the separated permissions associated to the user.

Can i transform this in some eloquent relationship like hasMany, belongsToMany, etc... ?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2BROml7
via IFTTT

Aucun commentaire:

Enregistrer un commentaire