我创建依赖于多个参数的查询。例如,当控制器函数获得“价格”和“状态”参数时,我想基于这两个参数返回结果。
当我使用一个参数时,一切正常。
有我的控制器的例子。
$productList = Product::
where([
['lat', '>', $calculateDistanceDifference->getData()->latDifferenceBottom],
['lat', '<', $calculateDistanceDifference->getData()->latDifferenceTop],
['lng', '>', $calculateDistanceDifference->getData()->lngDifferenceBottom],
['lng', '<', $calculateDistanceDifference->getData()->lngDifferenceTop]
])
->when(request('price') !== "", function ($q) {
if(request('price') === "0-20"){
return $q->where([['price', '>', 0], ['price', '<=', 20]]);
}else if(request('price') === "21-50"){
return $q->where([['price', '>', 20], ['price', '<=', 50]]);
}else if(request('price') === "51-100"){
return $q->where([['price', '>', 50], ['price', '<=', 100]]);
}else if(request('price') === "100-200"){
return $q->where([['price', '>', 100], ['price', '<=', 200]]);
}else if(request('price') === "201+"){
return $q->where('price', '>', 200);
}
})
->when(request('status') !== "", function ($q) {
if(request('status') === "new"){
return $q->where('status', 0);
}else if(request('status') === "old"){
return $q->where('status', 1);
}
})
->when(request('active') !== "", function ($q) {
if(request('active') == true){
return $q->where('state', 0);
}else{
var_dump(request('active'));
return $q->where('state', 1);
}
})
->with('productPhotos')
->with('categories')
->with('users')
->get();
在所有转换后如何避免返回语句和返回结果?
感谢您的帮助。
答案 0 :(得分:0)
您可以通过if / else或任何编程语句来拆分和合并查询。
例如
$productList = Product::select('*');
if (request('price') !== ""){
if(request('price') === "0-20"){
$productList = $productList->where('price', '>', 0)->where('price', '<=', 20);
}
//any other conditions that you want to handle....
}
if (request('status') !== ""){
if(request('status') === "new){
$productList = $productList->where('status', '=', 0);
}
//any other conditions that you want to handle....
}
$productList = $productList
->with('productPhotos')
->with('categories')
->with('users')
->get();
希望获得帮助。