mardi 28 août 2018

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).

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

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');
    }
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire