【问题标题】:Use whereHas to find all items that doesn't have specific value (for example User and Role - get all user that does not have admin role)使用 whereHas 查找所有没有特定值的项目(例如 User 和 Role - 获取所有没有管理员角色的用户)
【发布时间】:2020-02-11 22:34:13
【问题描述】:

我有两个模型,用户和角色。每个用户都有许多角色,如“管理员”、“简单用户”等。 我想获取所有没有“管理员”角色的用户。我知道这可以通过加入查询来解决。但我想使用“wherHas()”函数。

User table has id, name
Role table has id, slug, name
user_role as pivot table has user_id and role_id

在用户模型中

public function roles()
{
    return $this->belongsToMany('App\Role');
}

在角色模型中

public function users()
{
    return $this->belongsToMany('App\User');
}

查询示例:

$users = User::whereHas('roles', function ($query){
    $query->where('slug', '!=', 'ecoyar');
  })->get(); 

对不起我的英语!

【问题讨论】:

  • 您需要提供更多细节:这两个模型是如何联系起来的?每个模型中有哪些列?为什么你不能只做$users = User::where('role', '!=', '1)->get()
  • 我根据我的情况更新了我的问题。

标签: laravel


【解决方案1】:

How to query the absence of a relationship:

use Illuminate\Database\Eloquent\Builder;

$users = App\User::whereDoesntHave('roles', function (Builder $query) {
    $query->where('slug', 'like', 'ecoyar');
})->get();

【讨论】:

  • 谢谢,它对我有用,但它在 Laravel 文档中吗?!
  • 点击链接:)
猜你喜欢
  • 1970-01-01
  • 2020-02-16
  • 2012-07-06
  • 1970-01-01
  • 2023-03-21
  • 2021-11-17
  • 2016-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多