Skip to content
Advertisement

Laravel Eloquent – Get many-relationship of many-relationship

Assume the following structure:

A user has many projects. A project has many tasks.

Goal: I want to get all tasks of a certain $user. What is the most elegant way to achieve this?

What I am currently using is a big, non intuitive function chain that returns a collection instead of a collection builder instance:

return $user->projects()->with('tasks')->get()->pluck('tasks')->flatten();

This is what the relationships look like:

class User extends IlluminateDatabaseEloquentModel {
    public function projects(){
        return $this->hasMany(Project::class);
    }
}

class Project extends IlluminateDatabaseEloquentModel {
    public function tasks(){
        return $this->hasMany(Task::class);
    }
}

Advertisement

Answer

Has Many Through relationship is a bit complicated to understand a provide shortcut way to access data of another mode relation.
In your User model make relationship like this way :

public function tasks()
{
   return $this->hasManyThrough(
     Task::class,
     Project::class,
     'user_id', // Foreign key on projects table...
     'project_id', // Foreign key on tasks table...
     'id', // Local key on users table...
     'id' // Local key on projects table...
   );
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement