Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 通过2个字段雄辩地进行搜索_Mysql_Laravel 5_Eloquent - Fatal编程技术网

Mysql 通过2个字段雄辩地进行搜索

Mysql 通过2个字段雄辩地进行搜索,mysql,laravel-5,eloquent,Mysql,Laravel 5,Eloquent,在Laravel 5.6/MySQL 5.7中,有没有一种方法可以雄辩地使用条件进行搜索: 需要检查是否设置了销售价格,然后在销售价格中搜索,或者在零售价格中搜索 我是否使用了以下条件: \DB::raw( ‘ isNull( sale_price, retail_price ) > 10’ ) 如果销售价格和零售价格都为空,如何修改上面的搜索 还是有更好的解决办法 修改: 我将其作为范围实施: public function scopeGetByDoublePrice($que

在Laravel 5.6/MySQL 5.7中,有没有一种方法可以雄辩地使用条件进行搜索:

  • 需要检查是否设置了销售价格,然后在销售价格中搜索,或者在零售价格中搜索
我是否使用了以下条件:

  \DB::raw( ‘ isNull( sale_price, retail_price ) > 10’ )
如果销售价格和零售价格都为空,如何修改上面的搜索

还是有更好的解决办法

修改:

我将其作为范围实施:

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;
}
公共函数scopeGetByDoublePrice($query,$price\u from=null,$price\u to=null)
{
//需要检查是否设置了销售价格,然后在销售价格中搜索,或者在零售价格中搜索
if(空($price\u-from)和空($price\u-to))返回$query;
如果设置了(!empty($price_from)){/$price_from
$query->whereNotNull('sale_price')->where('sale_price','>=','price_from');
$query->orWhere('retail_price','>=',$price_from);
}//如果设置了(!empty($price\u from)){//$price\u from
如果设置了(!empty($price_to)){/$price_to

$query->whereNotNull('sale_price')->where('sale_price','用于以下约束:

$price = 10;
$builder->where(function($query) use ($price) {
  $query->whereNotNull('sale_price')->where('sale_price', '>', $price);
  $query->orWhere('retail_price', '>', $price);
});
这将向您的查询中添加以下内容:

AND (sale_price IS NOT NULL and sale_price > 10 OR retail_price > 10)

重要的是,你会发现括号中包含的额外约束可以让你避免这种情况,当其他约束因为

而被忽略时,为什么不使用
->where('sale_price',10',>)->where('retail_price',10',>)之类的东西呢
这将以同样的方式工作。或者类似于
->where('sale_price','>',10)->或者where('retails_price','>',10)
谢谢!我修改了原始内容,请看一看。只需像我在回答中那样在where()调用中包装范围约束-这将为您提供所需的()