简体   繁体   中英

write a query with eloquent in laravel

How can I write this query using an Eloquent model? I need to get users who have admin or seller roles.

$users = DB::table('users')
    ->where('users.verified' , 1)
    ->join('role_user' , 'role_user.user_id' , '=' , 'users.id')
    ->join('role' , 'role_user.role_id' , '=' , 'role.id')
    ->where('role.title' , 'seller')
    ->orWhere('role.title' , 'admin')
    ->get();

Models

class User extends Model
{
    public function role()
    {
        return $this->belongsToMany(Role::class);
    }
}


class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class);
    }
}

If you want to use Eloquent, and query any entity to return only results where a relationship exists and meets criteria you can use the whereHas() method with a subquery.

User::where('verified', 1)
    ->whereHas('role', function($query) {
        $query->whereIn('title', ['seller', 'admin']);
    })->get();

It is the same syntax in reverse depending on which entity you want at the top level.

Role::whereIn('title', ['seller', 'admin'])
    ->whereHas('users', function($query) {
        $query->where('verified', 1);
    })->get();

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