【问题标题】:filtering query in laravellaravel 中的过滤查询
【发布时间】:2020-08-30 13:58:17
【问题描述】:

我已经在 laravel 中写了一个过滤查询

    $data = DB::table('products')->DISTINCT('modalid')->DISTINCT('brandid')->select('rimdiameter','modalid','modalname1','modalname2','image1','brand','minprice','maxprice')
->when($centre_bore, function($query,  $centre_bore){
    $query->where('hubbore','>=',$centre_bore);
})->when($boltptn, function($query, $boltptn) {
    $query->where('boltpattern',$boltptn);
})->when($diameter, function($query, $diameter) {
    $query->where('rimdiameter',$diameter);
})->when($width, function($query, $width) {
    $query->where('rimwidth',$width);
})->when($frontwid, function($query, $frontwid) {
    $query->where('rimwidthfront',$frontwid);
})->when($construct, function($query, $construct) {
    $query->where('construction',$construct);
})->when($color, function($query, $color) {
    $query->where('modalname2',$color);
})->when($brand, function($query, $brand) {
    $query->where('brand',$brand);
})->get();

它可以工作,但是 rimdiameter=22 、 rimwidth=11 和 rimwidthfront=9 是用户选择的值,在上述情况下没有数据,但我希望查询像 rimdiameter=22 、 rimwidth=11 和 rimdiameter=22 一样工作, rimwidthfront=9 这个如何为这个结果编写查询?其他字段在某些时候是无能为力的,因为值是空的,所以我在什么时候使用,如何在我的查询中实现上述要求..

【问题讨论】:

  • 我认为你应该使用where() 子句而不是when()
  • @hacker315 我不太明白
  • 请看下面的答案。看看有没有帮助。
  • 你没有在你的问题中提到它..
  • 你能分享一个请求的例子,你得到什么和期望值。你的问题不是很清楚

标签: php mysql laravel filtering


【解决方案1】:

使用 where('rimwidth','=',$width)

因为函数需要三个参数:

  1. 列名
  2. 符号
  3. 价值观

【讨论】:

    【解决方案2】:

    试试下面:

    $data = DB::table('products')->DISTINCT('modalid')->DISTINCT('brandid')->select('rimdiameter','modalid','modalname1','modalname2','image1','brand','minprice','maxprice')
    ->where(function ($query) use ($diameter,$width,$frontwid) {
        $query->where('rimdiameter', '=', $diameter)
               ->where('rimwidthfront', '=', $frontwid)
            ->orWhere('rimdiameter', '=', $diameter)
            ->where('rimwidth', '=', $width);
    })
    

    【讨论】:

      猜你喜欢
      • 2014-10-18
      • 1970-01-01
      • 2016-01-09
      • 2018-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      相关资源
      最近更新 更多