Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel count Eloquent belongsToMany related model

I'm new to Laravel, and I got stuck with the following issue: I have a table for the users, and groups, and a table for connecting them. The general task any user can join any group.

----------------------------------------------
| users        | groups     | user_groups    |
|--------------------------------------------|
| id - int pk  | id - pk    | id - pk        |
| name text    | name       | user_id - fk   |
| email        |            | group_id - fk  |
| phone        |            | any_attr       |
----------------------------------------------

I have the following models:

class User
{
    ...
    public function groups()
    {
        return $this->belongsToMany(Group::class, 'user_groups')->withPivot(['is_notification_requested']);
    }
    ...
}


class Group
{
    ...
    public function users()
    {
        return $this->belongsToMany(User::class, 'user_groups');
    }
    ...
}

How do I get all of the groups, with a count of the members? I need the Group model, and a count of the users in the group.

like image 823
Zoltán Fekete Avatar asked Sep 26 '16 18:09

Zoltán Fekete


People also ask

How do you count relationships?

The relations of a set will be the various possible collections of ordered pairs. For example {(1,1),(1,2)} is a relation. So too is {(1,1)} and so too is {(1,1),(1,2),(2,1)} etc...

What is with () in Laravel?

with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.

How do you define many relationships in Laravel?

As we have defined the hasMany relationship on Brand model which return the related records of Product model, we can define the inverse relationship on the Product model. Open your app/Product. php model file and add a new method called brand() in it which will return the related brand of a product.

What is BelongsTo in Laravel?

BelongsTo is a inverse of HasOne. We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with User and Phone models. I'm giving hasOne relation from User to Phone. class User extends Model { /** * Get the phone record associated with the user.


1 Answers

If you're using Laravel 5.3, you can simply add withCount('relationship') as documented here: https://laravel.com/docs/5.3/eloquent-relationships#counting-related-models

Here's an example following your code:

$groups = Group::withCount('users')->get();

Now you can do this:

foreach($groups as $group) {
    echo $group->user_count
}
like image 94
ollieread Avatar answered Oct 19 '22 23:10

ollieread