0

How can i filter the max value of a 'price' field in a different table?

Current code:

$query = Product::join('variants', 'variants.product_id', '=', 'products.id');

$query->select('products.*',  DB::raw("MAX(variants.price) as max_variant_price"));

if($params['priceFrom'] !== false) {
    $query->whereRaw('max_variant_price >= ' .$params['priceFrom']);
}
if($params['priceTo'] !== false) {
    $query->whereRaw('max_variant_price <=' . $params['priceTo']);
}

But getting the following error: Column not found: 1054 Unknown column 'max_variant_price' in 'where clause'.

Paul
  • 858
  • 2
  • 10
  • 27
  • Try to use `MAX(variants.price)` in your where clause instead of `max_variant_price ` and see if it works – djunehor Nov 07 '19 at 17:13
  • You can only use aggregates for comparison in the HAVING clause: https://stackoverflow.com/questions/3284409/use-mysql-sum-in-a-where-clause – Vladan Nov 07 '19 at 17:39

1 Answers1

0
$getMaxValue= Product::join('variants.product_id', '=', 'products.id')-> 
(select('name','type', DB::raw('max(variants.total) as total'))->
where(total, '>=' , $request->price)->get();
snieguu
  • 2,073
  • 2
  • 20
  • 39