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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2Mza3gB
via IFTTT

Aucun commentaire:

Enregistrer un commentaire