我正在使用Laravel Eloquent查询构建器,我有一个查询,我想在多个条件下使用 WHERE
子句 . 它有效,但它并不优雅 .
例:
$results = User::where('this', '=', 1)
->where('that', '=', 1)
->where('this_too', '=', 1)
->where('that_too', '=', 1)
->where('this_as_well', '=', 1)
->where('that_as_well', '=', 1)
->where('this_one_too', '=', 1)
->where('that_one_too', '=', 1)
->where('this_one_as_well', '=', 1)
->where('that_one_as_well', '=', 1)
->get();
有没有更好的方法来做到这一点,还是我应该坚持这种方法?
18 回答
要么
要么
您可以在匿名函数中使用子查询,如下所示:
没有一个真实的例子,很难提出建议 . 但是,我从来不需要在查询中使用那么多WHERE子句,这可能表明数据结构存在问题 .
了解数据规范化可能会有所帮助:http://en.wikipedia.org/wiki/Third_normal_form
Conditions using Array:
Will produce query like bellow:
Conditions using Antonymous Function:
Will produce query like bellow:
根据我的建议,如果你正在进行过滤或搜索
那你应该去:
在这种情况下,你可以使用这样的东西:
它应该为您提供如下查询:
您可以在where子句中使用array,如下所示 .
使用
whereIn
条件并传递数组$array = [1008,1009,1010];
User::whereIn('users.id', $array)->get();
whereColumn
方法可以传递多个条件的数组 . 这些条件将使用and
运算符连接 .Example:
有关更多信息,请查看文档的这一部分https://laravel.com/docs/5.4/queries#where-clauses
Multiple where clauses
finally getting the result
您可以在 Laravel 5.3 中使用雄辩
所有结果
部分结果
In Laravel 5.3 你可以使用更多颗粒状的wheres作为数组传递:
就个人而言,我没有在多个
where
调用中找到用例,但事实是你可以使用它 .Since June 2014 you can pass an array to where
只要您希望所有
wheres
使用and
运算符,您就可以这样对它们进行分组:然后:
以上将导致此类查询:
查询范围可以帮助您使代码更具可读性 .
http://laravel.com/docs/eloquent#query-scopes
用一些例子更新这个答案:
在您的模型中,创建这样的范围方法:
然后,您可以在构建查询时调用此范围:
请务必将任何其他过滤器应用于子查询,否则可能会收集所有记录 .