【问题标题】:With eloquent to make search by 2 fields雄辩地通过2个字段进行搜索
【发布时间】: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 类似-&gt;where('sale_price', 10, '&gt;')-&gt;where('retail_price ', 10, '&gt;') 这样的方式也一样。
  • 或类似-&gt;where('sale_price', '&gt;' ,10)-&gt;orWhere('retails_price' , '&gt;' , 10)

标签: mysql laravel-5 eloquent


【解决方案1】:

使用以下约束:

$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)

重要的是,您会发现括号中包含的那些额外约束可以避免由于 OR 而忽略其他约束的情况。

【讨论】:

  • 谢谢!我修改了原创内容,你能看一下吗?
  • 只需像我在回答中所做的那样将范围约束包装在 where() 调用中 - 这将为您提供所需的 ()
猜你喜欢
  • 1970-01-01
  • 2015-05-08
  • 2020-04-26
  • 1970-01-01
  • 2018-07-26
  • 2017-06-28
  • 2020-03-19
  • 2021-05-12
  • 1970-01-01
相关资源
最近更新 更多