PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 26, 2022

[FIXED] Group by query Laravel

 February 26, 2022     eloquent, laravel     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing