首页 > 解决方案 > Laravel BelongsToMany 与 WhereHas 条件的关系

问题描述

我的数据库中有一些关系:

public function managers()
{
   return $this->belongsToMany(User::class, 'manager_location', 'location_id', 'manager_id')
}

这种关系运作良好 - 返回与某个位置同步的所有用户。我正在使用spatie/laravel-permissions,我的用户有不同的角色。当我尝试返回具有某些角色的用户(添加whereHas到关系中)时,它会继续返回所有记录:

public function managers()
    {
        return $this->belongsToMany(User::class, 'manager_location', 'location_id', 'manager_id')->whereHas('roles', function ($q) {
            $q->where('name', '=','manager');
        });
    }

我哪里出错了?

PS Mysql日志查询:

select * from `users` inner join `manager_location` on `users`.`id` = `manager_location`.`manager_id` where `manager_location`.`location_id` is null and exists (select * from `roles` inner join `model_has_roles` on `roles`.`id` = `model_has_roles`.`role_id` where `users`.`id` = `model_has_roles`.`model_id` and `model_has_roles`.`model_type` = ? and `name` = ?)

QueryBuilder 转储:https ://pastebin.com/j6ik35mK

标签: laraveleloquent

解决方案


推荐阅读