jeudi 24 août 2017

eloquent: query many to many relationship

I create many to many relationship between users and roles like this:

User Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}

Role model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}

my question is how I can get only users that belongs to some specific role name, for example if I have a role name called "author", I want to get all author users, something like this in sql:

SELECT users.id, users.name 
FROM users, roles, role_user 
WHERE users.id = role_user.user_id
AND role_user.role_id = roles.id
AND roles.name="author";

note: I'm using Laravel 5.4



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

Aucun commentaire:

Enregistrer un commentaire