John
John

Reputation: 375

Laravel filter models by count of related models

I have a list of Groups with Users. Groups has a property maximum_users. Users can register in a Group only if they have a free place (If count of registered users in that Group does not exceed maximum_users property of that Group).

I can filter groups after selecting them with this condition:

$group->maximum_users >= $group->users()->count()

but in this case pagination doesn't work.

Table structure:

groups
    id - integer
    maximum_users - integer

users
    id - integer
    group_id - integer

Models:

class Group extends Model
{
    public function users()
    {
        return $this->hasMany('App\Models\User');
    }
}


class User extends Model
{
    public function group()
    {
        return $this->belongsTo('App\Models\Group');
    }
}

Upvotes: 0

Views: 95

Answers (1)

Erubiel
Erubiel

Reputation: 2972

How can I select only Groups with free places where Users can register? I need to paginate the results.

i would strongly recommend to use a pivot table, unless user can only be in one group, with pivot table something like this should work:

Group::whereRaw('(SELECT COUNT(*) 
                  FROM groups_users 
                  WHERE group_id = group.id) < group.maximum_users')
    ->paginate(15);

With your current structure

Group::whereRaw('(SELECT COUNT(*) 
                  FROM users 
                  WHERE group_id = groups.id) < groups.maximum_users')
    ->paginate(15);

Upvotes: 1

Related Questions