Ask Your Question
2

How to count relationship column in Laravel using GroupBy?

asked 2022-09-26 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-03-24 17:00:00 +0000

scrum gravatar image

To count the relationship column in Laravel using GroupBy, you can use the following code:

$counts = YourModel::with('relationship')->select('relationship_id', \DB::raw('COUNT(*) as total'))->groupBy('relationship_id')->get();

Explanation: 1. You start by calling the with() method to load a relationship with your model. 2. Next, you use the select() method to select the relationship column you want to group by and a raw query to count the occurrences of each relationship ID column. 3. Then, you use the groupBy() method to group the counts by the relationship column. Finally, you call the get() method to retrieve the count data.

This will return an array of objects, each containing the relationship column and the count of its occurrences. You can access the count for a specific relationship by using $counts->total attribute of the object.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-09-26 11:00:00 +0000

Seen: 10 times

Last updated: Mar 24 '23