Jav*_*ved 1 laravel laravel-5.5
我很迷惑关于与搜索min-max值.在我的posts桌子上有一两场min_price和max_price,在我搜索有一对夫妇,我需要覆盖的搜索查询的事情.
如果用户仅搜索max_value,则显示所有价格为的帖子less than or equal to max_value.
如果用户仅搜索min_value,则显示所有价格为的帖子less than or equal to min_value.
如果用户使用min_value和搜索max_value,则显示所有价格介于两者之间的帖子min_value and max_value.
如果两者都为null,则返回所有帖子.
我怎样才能做到这一点 ?
我的代码:
$searchablePost = Post::with(['product','postattribute.attribute.category','user.userDetails'])
->whereIn('product_id', $userApprovalProductIDs)
->whereIn('demand_or_supply', $demand_or_supply);
// skip my search query code
$searchedPost = $searchablePost->offset($offset)->limit($limit)->orderBy('id','desc')->get();
Run Code Online (Sandbox Code Playgroud)
我该怎么办?
检查:
1.如果两者(最小值和最大值)都可用(即非空):
2.如果最小值可用:
3.如果最大值可用:
// if none of them is null
if (! (is_null($min_value) && is_null($max_value))) {
// fetch all between min & max values
$searchablePost = $searchablePost->whereBetween('price', [$min_value, $max_value]);
}
// if just min_value is available (is not null)
elseif (! is_null($min_value)) {
// fetch all greater than or equal to min_value
$searchablePost = $searchablePost->where('price', '>=', $min_value);
}
// if just max_value is available (is not null)
elseif (! is_null($max_value)) {
// fetch all lesser than or equal to max_value
$searchablePost = $searchablePost->where('price', '<=', $max_value);
}
Run Code Online (Sandbox Code Playgroud)
如果您有min_price&的单独字段max_price,如评论中所述,只需更改代码如下:
if (! (is_null($min_value) && is_null($max_value))) {
$searchablePost = $searchablePost
->where('min_price', '>=', $min_value)
->where('max_price', '<=', $max_value);
}
elseif (! is_null($min_value)) {
$searchablePost = $searchablePost->where('min_price', '>=', $min_value);
}
elseif (! is_null($max_value)) {
$searchablePost = $searchablePost->where('max_price', '<=', $max_value);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
425 次 |
| 最近记录: |