11.08.2017 Views

codebright

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Eloquent Relationships 357<br />

13 $album->artist()->associate($artist);<br />

14 $album->save();<br />

15<br />

16 return View::make('hello');<br />

17 });<br />

Wait, what’s this new line?<br />

1 $album->artist()->associate($artist);<br />

Let’s break the method chain down. Here’s the first method.<br />

1 $album->artist();<br />

Do you remember that method? That’s the relationship method that we created on the Album object.<br />

So what exactly does it return? The method returns an instance of the Eloquent query builder, just<br />

like the the one that we used in a previous chapter.<br />

However, this query builder instance will have some constraints placed on it for us. The current set<br />

of results represented by the query builder will be the related Artists (in this case, a collection of<br />

one) to our Album.<br />

It’s the same as the following.<br />

1 Artist::where('album_id', '=', __OUR__CURRENT__ALBUM__);<br />

That’s handy right? We could chain on more queries if we wanted to. For example:<br />

1 $album->artist()->where('genre', '=', 'rock')->take(2);<br />

Be sure to remember that the query builder required a trigger method at the end of the join to return<br />

a result collection. Like this:<br />

1 $album->artist()->where('genre', '=', 'rock')->take(2)->get();<br />

This also means that we can retrieve a full collection of related artists by performing the following.<br />

1 $album->artist()->get();<br />

Or, a single instance using the first() trigger method.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!