Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GodziLaravel's avatar

Eloquent: how to group results by a specific filed then get the sum of values?

Hello ,

From Score model I need to return all results where target_score > current_score, so I :

return Score::whereRaw(
            'target_score > current_score'
        )->get();

Then the result is :

| id | language_id | target_score | current_score | student_id |
|----|-------------|--------------|---------------|------------|
| 1  | 1           | 8            | 3             | 50         |
| 2  | 1           | 8            | 6             | 10         |
| 3  | 13          | 8            | 1             | 15         |
| 7  | 13          | 6            | 4             | 46         |
| 13 | 13          | 6            | 5             | 45         |
| 15 | 13          | 7            | 6             | 45         |
| 17 | 22          | 9            | 2             | 45         |
| 18 | 22          | 9            | 3             | 17         |
| 22 | 22          | 10           | 4             | 145        |

Now what I'm looking for is to get two fields in the result :

  • Field1: (sum of target_score - sum of current_score) by language_id
  • Field2: count of students per each row of filed1

So the result should be like :

| language_id | Field2              | Field2         |
|-------------|---------------------|----------------|
| 1           | (8+8)-(3+6)         | [50,10]=>2     |
| 13          | (8+6+6+7)-(1+4+5+6) | [15,46,45]=>3  |
| 22          | (9+9+10)-(2+3+4)    | [45,17,145]=>3 |

Thanks

0 likes
2 replies
SilenceBringer's avatar
Level 55

@godzilaravel like this

Score::select([
    'language_id',
    DB::raw('sum(target_score - current_score) as field1'),
    DB::raw('count(student_id) as field2')
])
    ->whereColumn('target_score', '>', 'current_score')
    ->groupBy('language_id')
    ->get()

Please or to participate in this conversation.