这个多重可选过滤器的最佳解决方案是什么? [英] What will the best solution for this multiple optional filter?
问题描述
这些都是可选字段,因此我将不得不编写带有条件的多个查询,还是有什么方法可以使用Laravel处理呢?查询将是什么样子?
These are all optional fields, so will I have to write multiple queries with conditions or is there any way to handle this using Laravel? What will be the query looks like?
谢谢
推荐答案
这在一定程度上取决于过滤器的提交方式,但是您可以执行以下两项操作之一(可能还要花费数百万之多……):
It depends a bit on how the filters are submitted, but you can do one of the following two things (and probably a gazillion more...):
public function listCars(Request $request)
{
$cars = Car::when($request->get('make'), function ($query, $make) {
$query->where('make', $make);
})
->when($request->get('model'), function ($query, $model) {
$query->where('model', $model);
})
->...
->get();
// do what you have to do
}
因此,您基本上是将查询生成器调用包装在when($value, $callback)
中,如果$value
的计算结果为true,则仅执行$callback
.当您使用$request->get('parameter')
检索未设置的参数时,它将返回null且不执行回调.但是要小心,如果$value
是0
,它也不会执行回调.因此,请确保您没有将此作为索引.
So you are basically wrapping your query builder calls in when($value, $callback)
, which will only execute $callback
if $value
evaluates to true. When you retrieve a not set parameter with $request->get('parameter')
, it will return null and the callback is not executed. But be careful, if $value
is 0
it will also not execute the callback. So be sure you don't have this as an index.
作为替代方案,您也可以做同样的事情,但是用更少的口才来表达……
As alternative to this, you can also do the same thing but with a bit less eloquent expressions...
public function listCars(Request $request)
{
$query = Car::query();
if($request->filled('make')) {
$query->where('make', $request->get('make'));
}
if($request->filled('model')) {
$query->where('model', $request->get('model'));
}
// some more filtering, sorting, ... here
$cars = $query->get();
// do what you have to do
}
这篇关于这个多重可选过滤器的最佳解决方案是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!