John Dorean
John Dorean

Reputation: 3874

Retrieving all records through multiple hasMany relationships

Apologies for the vague title, I'm not quire sure if there's a name for this.

I basically have the following relationship between my models in my Laravel 4 application:

User -----< Template -----< Job

(users haveMany templates, templates haveMany jobs).

I want to retrieve all the jobs for a user (by their ID). Normally I'd do:

Job::where('user_id', '=', Auth::user()->id);

But the link between jobs and users exists through the templates table, so I tried doing this:

$jobs = Auth::user()->templates->jobs;

But that gives me an error about the $jobs property not existing:

Undefined property: Illuminate\Database\Eloquent\Collection::$jobs

How can I retrieve all the jobs for a user in this scenario? I'd prefer not making a relationship between User and Job, as it seems like I'm just duplicating the relationship that's already there?

Thanks.

Upvotes: 0

Views: 59

Answers (1)

patricus
patricus

Reputation: 62278

Laravel has a hasManyThrough relationship. If User hasMany Template, and Template hasMany Job, you can setup a User hasMany Job through Template relationship.

User model:

public function jobs() {
    return $this->hasManyThrough('Job', 'Template');
}

With that relationship, you access the user's jobs via:

$jobs = Auth::user()->jobs;

With this, it is not duplicating a relationship that already exists; it is just setting up the syntax to use the existing relationships the way you need to. You don't need to change any fields or modify any data.

Upvotes: 1

Related Questions