Saturday, February 26, 2022

[FIXED] Group by query Laravel

Issue

I have two Models, cards and risks

Cards has the following columns:

1. id
2. weight
3. color  //There are four types of colors, green, red, yellow, blue

Risks has the following:

1. id
2. name
3. description
4. card_id

What I want to achieve is a count of how many risks are, grouped by colors, for example:

'color' => 'green'
'count' => '4'

'color' => 'blue'
'count' => '2'

'color' => 'red'
'count' => '6'

So far I haven't been able to make this query using Eloquent, maybe some DB::raw could help?

Any help would be appreciated


Solution

Risk::select('card.name', DB::raw('count(risks.card_id)'))
->rightJoin('cards', 'card.id', '=', 'risks.card_id')
->groupBy('risks.card_id')
->get();



Answered By - Mohamed Abdallah

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.