Home > Blockchain >  Count number of elements via Laravel relationship
Count number of elements via Laravel relationship

Time:06-01

There are different types of boards, types can have multiple boards, and boards have multiple users.

Task: get the number of users for a specific type of boarding.

Model for types boarding:

class BoardingType extends Model
{
    public function boardings()
    {
        return $this->hasMany(Boarding::class, 'type');
    }
}

Model for boardings:

class Boarding extends Model
{
    public function users()
    {
        return $this->hasMany(User::class, 'boarding');
    }
}

How can I concisely get all users for boarding types?

Made in a similar form, I do not like the implementation:

foreach ($types as $type) {
    $usersCount = 0;
    foreach ($type->boardings as $boarding) {
        $usersCount  = $boarding->users()->count();
    }
}

CodePudding user response:

You may use the has-many-through relationship here.
In your BoardingType model

  public function users()
    {
        return $this->hasManyThrough(User::class, Bording::class);
    }

Please note that you may have to specify the fk in case your model doesn't follow the laravel key convention:

 public function users()
    {
        return $this->hasManyThrough(
            User::class,
            Bording::class,
            'bording_type_id', // Foreign key on the boarding table...
            'boarding_id', // Foreign key on the users table...
            'id', // Local key on the bording type table...
            'id' // Local key on the boarding table...
        );
    }

you can count the number of users for a bording type like this:

$usersCount = $bordingType->users()->count();
  • Related