11.08.2017 Views

codebright

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Eloquent Relationships 352<br />

We are going to build a system using Artists, Albums and Listeners. Listeners are simply users that<br />

like to listen to a variety of albums. Let’s think about the relationships.<br />

• An Artist has_many Albums.<br />

• An Album belongs_to an Artist.<br />

• A Listener belongs_to_many Albums.<br />

• An Album belongs_to_many Listeners.<br />

We have a simple relationship between an Artist and many Albums, and a many to many<br />

relationship between Listeners and Albums. So let’s think about our table structure. If an Album<br />

belongs_to an Artist then the identifying foreign key for the relationship will exist on the Album<br />

table. The many to many relationship will require a pivot table.<br />

We know that Eloquent required a plural form of the model for its table name (unless we specify<br />

otherwise), but how do we name the pivot table? The default format for the pivot table is the singular<br />

form of the two related models separated by an _ underscore. The order of the instances should be<br />

alphabetical. This means that our pivot table is called album_listener.<br />

All foreign key columns follow a similar naming convention. The singular form of the related model<br />

appended with _id. Our pivot table will contain both album_id and listener_id.<br />

Let’s look at the constructed migration, then we will examine anything that’s new in more detail.<br />

1

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

Saved successfully!

Ooh no, something went wrong!