Batch
6 days ago

Eloquent Select for three hasMany relations

Posted 6 days ago by Batch

My models are below:

Organization:

class Organization extends Model
{
    public function departments()
    {
        return $this->hasMany('App\Department');
    }
}

Departments:

class Department extends Model
{
    public function organization()
    {
        return $this->belongsTo('App\Organization');
    }

    public function units()
    {
        return $this->hasMany('App\Unit');
    }
}

Units:

class Unit extends Model
{
    public function department()
    {
        return $this->belongsTo('App\Department');
    }
}

Organizations have many departments. Departments have many units.

I want to select all units under a specific organization. How can I achive this?

I tried below query but it didn't work:

\App\Organization::find(1)->departments()->units

Please sign in or create an account to participate in this conversation.