sabri yasin
sabri yasin

Reputation: 3

How to get max value + other column using Laravel Eloquent

This is my query:

$maxvalue= market::whereBetween('created_at', [$from, $to])->max('price');

But in addition to the max value I also want to get the user_id column. How would I do that?

Upvotes: 0

Views: 3547

Answers (1)

aynber
aynber

Reputation: 23000

You won't be able to use the max() Eloquent function, but you can use MySQL's max() function with DB::raw(). You'll need to use groupBy as well so you can get it per user:

$maxValues = market::whereBetween('created_at', [$from, $to])
                 ->groupBy('user_id')
                 ->get(['user_id', DB::raw('max(price) as max_price'));

Upvotes: 1

Related Questions