Laravel Eloquent:在 where 添加过滤器(条件查询的 if-else)?

Hưn*_*ịnh 1 laravel eloquent laravel-5

我有这个代码:

$result = DB::table('product as p')
      ->join('master as cl', 'p.color', '=', 'cl.name')
      ->join('master as brand', 'p.brand', '=', 'brand.name')
      ->where('p.brand', $brandname)
      ->whereRaw("p.del_flag = 0  and cl.is_active = 1 and brand.is_active = 1 and p.product_type = 1")
      ->select('p.name')
      ->groupBy('p.name')
      ->orderBy('p.name')
      ->take(3)
      ->get();
Run Code Online (Sandbox Code Playgroud)

我需要添加过滤器:

if(isset($_POST['brand'])) {
    ->where('p.brand', $_POST['brand'])
}
if(isset($_POST['color'])) {
    ->where('p.color', $_POST['color'])
}
if(isset($_POST['product_type'])) {
    ->where('p.product_type', $_POST['product_type'])
}
Run Code Online (Sandbox Code Playgroud)

我看过很多关于 Laravel 中多个Where 的帖子,但没有一篇讨论那些特殊的Where。

如何在查询中添加过滤器?

Jer*_*dev 6

首先将查询传递给变量并更新查询变量。

$query = DB::table('product as p')
      ->join('master as cl', 'p.color', '=', 'cl.name')
      ->join('master as brand', 'p.brand', '=', 'brand.name')
      ->where('p.brand', $brandname)
      ->whereRaw("p.del_flag = 0  and cl.is_active = 1 and brand.is_active = 1 and p.product_type = 1")
      ->select('p.name')
      ->groupBy('p.name')
      ->orderBy('p.name')
      ->take(3);

if( isset($_POST['brand'])) {
    $query->where('p.brand', $_POST['brand'])
}
if (isset($_POST['color'])) {
    $query->where('p.color', $_POST['color'])
}
if (isset($_POST['product_type'])) {
    $query->where('p.product_type', $_POST['product_type'])
}

$result = $query->get();
Run Code Online (Sandbox Code Playgroud)

更新:
正如 @Amol Rokade 提到的,您还可以使用该when()函数:

$result = DB::table('product as p')
      ->join('master as cl', 'p.color', '=', 'cl.name')
      ->join('master as brand', 'p.brand', '=', 'brand.name')
      ->where('p.brand', $brandname)
      ->whereRaw("p.del_flag = 0  and cl.is_active = 1 and brand.is_active = 1 and p.product_type = 1")
      ->when(isset($_POST['brand']), function ($query) {
            $query->where('p.brand', $_POST['brand']);
      })
      ->when(isset($_POST['color']), function ($query) {
            $query->where('p.color', $_POST['color']);
      })
      ->when(isset($_POST['product_type']), function ($query) {
            $query->where('p.product_type', $_POST['product_type']);
      })
      ->select('p.name')
      ->groupBy('p.name')
      ->orderBy('p.name')
      ->take(3)
      ->get();
Run Code Online (Sandbox Code Playgroud)