【发布时间】:2018-06-08 03:35:06
【问题描述】:
在 Laravel 5.6/MySQL 5.7 中有没有一种方法可以用 eloquent 进行条件搜索:
- 需要检查是否设置了 sale_price,然后在 sale_price 中搜索,否则在 Retail_price 中搜索
我是否使用过类似的条件:
\DB::raw( ‘ isNull( sale_price, retail_price ) > 10’ )
如果sales_price和retail_price都为null,如何修改上面的搜索?
或者有更好的解决方案?
修改:
我将其实现为范围:
public function scopeGetByDoublePrice($query, $price_from= null, $price_to= null)
{
// need to check if sale_price is set then search in sale_price else in retail_price
if ( empty($price_from) and empty($price_to) ) return $query;
if ( !empty($price_from) ) { // $price_from is set
$query->whereNotNull('sale_price')->where('sale_price', '>=', $price_from);
$query->orWhere('retail_price', '>=', $price_from);
} // if (!empty($price_from) ) { // $price_from is set
if ( !empty($price_to) ) { // $price_to is set
$query->whereNotNull('sale_price')->where('sale_price', '<=', $price_to);
$query->orWhere('retail_price', '<=', $price_to);
} // if (!empty($price_to) ) { // $price_to is set
return $query;
}
但是设置 2 个值 31 和 33 我得到了不同的结果:
https://imgur.com/a/AYTJAJn 我预计只有第一行会在结果集中!
在 sql-editor 中,我手动设置“()”,如下:
选择sale_price, retail_price
来自articles
LEFT JOIN 品牌 AS b on b.id =articles.brand_id
LEFT JOIN article_inventories AS ai on ai.article_id =articles.id
WHERE ( (sale_price 不为空 AND sale_price >= '31' OR retail_price >= '31') AND
(sale_price 不为空 AND sale_price retail_price
它可以按我的需要工作。如果有办法在我的范围内设置“()”?
【问题讨论】:
-
为什么不使用
and类似->where('sale_price', 10, '>')->where('retail_price ', 10, '>')这样的方式也一样。 -
或类似
->where('sale_price', '>' ,10)->orWhere('retails_price' , '>' , 10)