【问题标题】:laravel Eloquent query WhereHas wrong resultlaravel Eloquent 查询 WhereHas 结果错误
【发布时间】:2021-05-28 02:13:28
【问题描述】:

我有两个表和关系如下 用户 用户表:

id name active
1 abc 1
2 xyz Null
3 abx 0

书桌:

id user_id name active
1 1 book1 0
2 2 book2 0
3 1 book3 0

关系是这样的 用户->书籍(HasMany)

return $this->hasMany(Book::class,'user_id','id');

我的查询如下

User::with('book')
->WhereHas('book', function($query) {
                    $query->where(['active'=> 1]);
                   })
->where(['id'=> 1,'active'=>1])
->get();

此查询获得零记录,因为书籍中的活动为 0

  1. 但我想查看所有用户记录,以及是否有匹配记录与书中的活动 1。
  2. second 是查询用户活动 1 或 Null,如果使用 ->orwhereNull('active') 所有记录都会更改。

谢谢

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    您在两个表上都有 idactive 列,所以我认为您需要像这样更改您的查询:

    User::with('book')
    ->WhereHas('book', function($query) {
             $query->where(['books.active'=> 1]); // books table active column
    })
    ->where(['id'=> 1,'active'=> 1]) // users table id, active column
    ->get();
    

    【讨论】:

    • 旁注,您不必在where() 子句中使用users.idusers.active,因为books 不是join()'ed。它不会伤害任何东西,只是为了清楚:)
    • @Tim 感谢您的解释,我已经编辑了我的答案
    • 但是如果 book 表中没有记录,它也不会显示用户记录
    • 如果书籍表上没有记录匹配,它不会显示用户。这是哪里有
    • @Mr.SH 我认为你应该用一个例子重新表述你的预期输出。这很令人困惑。
    【解决方案2】:

    我猜您需要对相关记录应用过滤器(with()),而不是对整个查询应用过滤器。因此,您将始终获得用户列表以及活动书籍列表

    User::with(['book'=> function($query) {
            $query->where('active', 1);
    }])
    ->where(function ($query) {
        $query->where('active', 1)
              ->orWhereNull('active');
    })
    ->get();
    

    我在这里使用了logical grouping,以防您在查询中添加更多过滤子句。

    或者你可以在你的用户模型中定义一个新的关系来只选择活跃的相关书籍作为

    class User extends Model
    {
        public function book()
        {
            return $this->hasMany(Book::class, 'user_id', 'id');
        }
        public function active_books()
        {
            return $this->hasMany(Book::class, 'user_id', 'id')
                ->where('active', '=', 1);
        }
    }
    
    
    User::with('active_books')
        ->where(function ($query) {
            $query->where('active', 1)
                  ->orWhereNull('active');
        })
        ->get();
    

    【讨论】:

      猜你喜欢
      • 2021-05-25
      • 2018-02-27
      • 1970-01-01
      • 2017-02-21
      • 2020-09-24
      • 2018-10-22
      • 2021-09-05
      • 2022-08-19
      • 2021-10-26
      相关资源
      最近更新 更多