Sebastien D
Sebastien D

Reputation: 4482

How to get the max value for elements having the same id under Laravel

Using Laravel/Eloquent, I would like to retrieve the max value for each week_id in the following table.

 +---------+-----------+
 | week_id |     value |
 +---------+-----------+
 |    5    |           |
 |    6    |         1 |
 |    6    |           |
 |    6    |           |
 |    7    |         3 |
 |    7    |         4 |
 |    7    |           |
 +---------+-----------+

With MySql I would do it like this:

SELECT week_id, max(value) as max_value FROM foo_table GROUP BY week_id

=>

+---------+-----------+
| week_id | max_value |
+---------+-----------+
|       5 |           |
|       6 |         1 |
|       7 |         4 |
+---------+-----------+

How could I achieve the same under Laravel?

Upvotes: 0

Views: 356

Answers (1)

yrv16
yrv16

Reputation: 2275

Try this:

 DB::table('foo_table')
    ->select('week_id', DB:raw('max(value) as max_value'))
    ->groupBy('week_id')
    ->get();

Upvotes: 2

Related Questions