如何在whereIn中处理null值?

时间:2017-10-04 11:25:54

标签: php laravel laravel-5 laravel-query-builder

我要执行以下查询,其中$category_id & $industry_id通过ajax请求作为数组发出。所以有时候$category_id & $industry_id可能是空值。那么当数组为空时如何避免该行语句呢?

$products = DB::table('users')
               ->join('products','products.auth_id','users.id')
               ->Join('reviews','products.id','reviews.product_id')
               ->select('products.*','users.avatar',DB::raw('(sum(rating)/count(user_id)) as rating'))             
               ->orwhereIn('products.category_id', [$request->get('category_id')])   
               ->orwhereIn('products.industry_id',[$request->get('industry_id')])   
               ->where('products.status','=','1')           
               ->groupBy('reviews.product_id')   
               ->latest()              
               ->get();

2 个答案:

答案 0 :(得分:1)

尝试此查询可以提供此帮助。

$query = DB::table('users')
   ->join('products','products.auth_id','users.id')
   ->Join('reviews','products.id','reviews.product_id')
   ->select('products.*','users.avatar',DB::raw('(sum(rating)/count(user_id)) as rating'))             
   ->where('products.status','=','1')           
   ->groupBy('reviews.product_id')   
   ->latest();

if ($request->has('category_id')) {
    $query->orWhereIn('products.category_id', $request->get('category_id'));
}

if ($request->has('industry_id')) {
    $query->orWhereIn(''products.industry_id', $request->get('industry_id'));
}
$products = $query->get();

答案 1 :(得分:0)

最简单的解决方案

    $query = DB::table('users')
       ->join('products','products.auth_id','users.id')
       ->Join('reviews','products.id','reviews.product_id')
       ->select('products.*','users.avatar',DB::raw('(sum(rating)/count(user_id)) as rating'))             
       ->where('products.status','=','1')           
       ->groupBy('reviews.product_id')   
       ->latest();

    if ($categoryId = $request->get('category_id')) {
        $query->orwhere('products.category_id', $categoryId);
    }

    if ($industryId = $request->get('industry_id')) {
        $query->orwhere('products.category_id', $industryId);
    }

    $products = $query->get();

BTW - 将orWhereIn更改为orWhere,看起来它仍然是一个值。