laravel belongsToMany Filter

那年仲夏 提交于 2021-02-08 04:10:32

问题


I have three tables as below:

users

id|name|username|password

roles

id|name

users_roles

id|user_id|role_id

These tables communicate via belongsToMany. I would like to find a way to select all data in “users” table except ones that their user value of "role_id" is 5 in table “users_roles”. How can I do it?


回答1:


You should use whereDoesntHave() to select models that don't have a related model meeting certain criteria:

$users = User::whereDoesntHave('roles', function($q){
    $q->where('role_id', 5);
})->get();



回答2:


Use Laravel's Query Builder:

<?php
$users = DB::table('users')
    ->leftJoin('users_roles', 'user.id', '=', 'users_roles.user_id')
    ->where('users_roles.role_id', '!=', 5)
    ->get();

http://laravel.com/docs/4.2/queries

Or using Eloquent directly:

<?php
$users = User::whereHas('users_roles', function($q)
{
    $q->where('role_id', '!=', 5);

})->get();

http://laravel.com/docs/4.2/eloquent#querying-relations




回答3:


<?php
$users = User::whereHas('roles', function($query) {
  $query->where('id', '<>', 5);
})
->orHas('roles','<', 1)
->get();



回答4:


I think the correct answer is:

    User::whereHas('roles', function ($query) {
        $query->whereId(5)
    }, '=', 0)->get();

This code should send a query that checks if the role with id=5 is related to the user or not.

Edit

While I think this should work but the @lukasgeiter answer is preferable.

In the end both methods use the has() to count the related models by using a subquery in the db query where clause but when you use the whereDoesntHave() it specifies the operator < and the count 1 itself.

You can var_dump(DB::getQueryLog()) in App::after()'s callback to see the actual query.



来源:https://stackoverflow.com/questions/28327703/laravel-belongstomany-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!