Reputation: 121
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 \Illuminate\Database\Eloquent\Model {
public function projects(){
return $this->hasMany(Project::class);
}
}
class Project extends \Illuminate\Database\Eloquent\Model {
public function tasks(){
return $this->hasMany(Task::class);
}
}
Upvotes: 0
Views: 543
Reputation: 34818
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...
);
}
Upvotes: 2