I get an error in the laravel query when I use the number (ranking) as the current product, then it did not find the production field

advertisements

I join My product table to review table then i count the rating of product then put condityion on rating then i got error that field not found.

Code:

  $products = Product::leftjoin('reviews','products.id','=','reviews.productID')
                           ->select('products.*',DB::raw("AVG(rating) as 'productRating'"))
                           ->where('products.status','=',"enable")
                           ->where(function($query) use ($categoriesID,$brands,$priceArray,$ratingArray)
                            {
                                $query->whereIn('categoryID',$categoriesID);
                                if(count($brands) > 0)
                                {
                                    $query->whereIn('brandID',$brands);
                                }
                                $query->whereBetween('productSellingPrice',$priceArray);
                                if(count($ratingArray) > 0)
                                {
                                    $query->whereBetween('productRating',$ratingArray);
                                }
                            })
                        ->groupBy('products.id')
                        ->get();

Error :

   SQLSTATE[42S22]: Column not found: 1054 Unknown column 'productRating' in 'where clause' (SQL: select `products`.*, AVG(rating) as 'productRating' from `products` left join `reviews` on `products`.`id` = `reviews`.`productID` where `products`.`status` = enable and (`categoryID` in (1, 3, 4, 8, 9, 11, 18, 21, 28, 31) and `productSellingPrice` between 50 and 5000 and `productRating` between 4 and 5) group by `products`.`id`)


This is SQL, not laravel, error.

You can not use aggregated field is where clause, you need to use having instead.

$products = Product::leftjoin('reviews','products.id','=','reviews.productID')
     ->select('products.*',DB::raw("AVG(rating) as 'productRating'"))
     ->where('products.status','=',"enable")
     ->whereIn('categoryID',$categoriesID)
     ->whereBetween('productSellingPrice',$priceArray)
     ->groupBy('products.id');

if(count($brands) > 0)
{
     $products->whereIn('brandID',$brands);
}

if(count($ratingArray) > 0)
{
    // assume $ratingArray = [$min, $max];
    list($ratingMin, $ratingMax) = $ratingArray;
    $products->having('productRating', '>', $ratingMin);
    $products->having('productRating', '<', $ratingMax);
}

$items = $products->get();