【问题标题】:whereBetween passing a value and nullwhereBetween 传递一个值和 null
【发布时间】:2018-02-10 10:56:43
【问题描述】:

我有一个雄辩的查询,我在其中传递了一个值和 null。例如,如果我有一个价格列并且我有两个变量$to$from

例如$from = 10 $to= ""

$from = 10;
$to = "";  
Product::whereBetween('price', [$from, $to])->get();

我的问题是这样可以吗,这行得通吗?如果没有,如果我想从10 搜索到infinity,我该怎么办?

【问题讨论】:

  • 你会指定,你想要10个区域记录还是只需要10个区域?

标签: php mysql laravel-5 laravel-eloquent


【解决方案1】:

您可以在 php 中使用?? 来检查空值,因此如果第一个值为空,它将等于您传递的第二个值。喜欢:

$from = $request->to ?? 0;
$to = $request->to ?? Model::max('column'); // names are imaginary

【讨论】:

    【解决方案2】:

    如果$to 可以是空值,您应该检查它并根据它构建不同的查询。
    例如:

    $products = Product::query();
    
    if(empty($to))
    {
       $products = $products->where('price','>=', $from);
    }
    else 
    {
       $products = $products->whereBetween('price', [$from, $to])
    }
    
    $products = $products->get();
    

    【讨论】:

      猜你喜欢
      • 2018-07-16
      • 1970-01-01
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-26
      • 2022-06-11
      • 1970-01-01
      相关资源
      最近更新 更多