【发布时间】: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 的值是多少?你给这个变量赋值了吗??