Home > Software design >  Laravel - Getting count of nested relationship
Laravel - Getting count of nested relationship

Time:09-27

I have an application where users can control their properties and leases.

These are the relationships defined:

//Team.php
/**
 * A team can have many properties.
 */
public function properties():
{
    return $this->hasMany(Property::class);
}
//Property.php
/**
 * A property can have many leases.
 */
public function leases():
{
    return $this->hasMany(Lease::class);
}

As you can see here, a Team can have many properties, and each property can also have many leases.

I am trying to figure out how I can get the number of leases that is associated with a Team:

$team = Auth::user()->currentTeam;

return $team->properties->leases->count();

However, the above code returns an error:

Property [leases] does not exist on this collection instance.

CodePudding user response:

You could add this method to your Team.php:

public function leasesCount(){
    return count(
        Team::
            join('properties', 'properties.team_id', '=', 'teams.id')
            ->join('leases', 'leases.property_id', '=', 'properties.id')
            ->where('teams.id', $this->id)
            ->get()
    );
}

CodePudding user response:

I ended up using a hasManyThrough relationship on the Team model, like so:

//Team.php

/**
 * Get all of the leases for the team.
 */
public function leases()
{
    return $this->hasManyThrough(Lease::class, Property::class);
}

Then I can simply get the number of leases created by a specific team by:

return $team->leases()->count();
  • Related