【问题标题】:Error with eloquent query雄辩的查询错误
【发布时间】:2018-01-16 10:53:14
【问题描述】:

我正在使用 Laravel 5.0

我基本上想要这种类型的查询:

(a='x' and b='y') 或 (a='xy')

users 拥有books

    $users= \App\User::whereHas('books', function($q) use ($x, $y){
        $q->where(function ($query) use ($x, $y){
            $query->where('a','=', $x)->where('b', '=',$y);
        })
        ->orWhere(function ($query2) use ($x, $y){
            $query2->where('a','=',$x.$y);
        });
    });

当然我有用户:

public function books()
{
    return $this->belongsTo('App\Book');
}

但如果检查通过"toSql()" 生成的 SQL,我会得到:

  from users where (select count(*) from books where 
    users.book_id = books.id 
    and 
    (a = ? and b = ?) 
    or 
    (a = ?)
  ) >= 1

这显然不是预期的查询,因为它会引发 users.book_id=books.id 部分可选,从而导致比应有的结果多得多。

所以,我的问题是:我在雄辩的查询中做错了什么?

【问题讨论】:

  • 请注意,您是否考虑过使用 DB::Raw 代替?
  • @LewisJohnson :不,因为我需要返回模型,而不是表条目。
  • 所以你可以使用 hydraRaw 否?
  • 我不知道,但是只有雄辩的才能得到我想要的结果吗?
  • $x 和 $y 的值是多少?你给这个变量赋值了吗??

标签: laravel eloquent


【解决方案1】:

没有必要有两个不同的嵌套 where。整个分组都应该在同一个括号内。

$users= \App\User::whereHas('books', function($q) use ($x, $y){
    $q->where(function ($query) use ($x, $y){
        $query->where('a','=', $x)
              ->where('b', '=',$y)
              ->orWhere('a','=',$x.$y);
    });
});

A and B or C 在功能上等价于 (A and B) or (C)

【讨论】:

  • 哇。谢谢!
猜你喜欢
  • 2015-07-07
  • 2018-01-26
  • 2014-04-12
  • 2021-07-23
  • 1970-01-01
  • 2017-11-11
  • 2020-01-14
  • 2017-02-17
相关资源
最近更新 更多