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 351<br />

1 +---------+------------------------+<br />

2 | id (PK) | name |<br />

3 +---------+------------------------+<br />

4 | 1 | Code Sexy |<br />

5 | 2 | Code Dutch |<br />

6 | 3 | Code Bright |<br />

7 | 4 | Code Happy |<br />

8 +----------------------------------+<br />

book_user<br />

1 +-------------------------+<br />

2 | id | user_id | book_id |<br />

3 +-----+---------+---------+<br />

4 | 1 | 1 | 2 |<br />

5 | 2 | 1 | 3 |<br />

6 | 3 | 2 | 2 |<br />

7 | 4 | 3 | 2 |<br />

8 +-----+---------+---------+<br />

Wait a minute, what’s that third table?<br />

Well spotted! That would be our join table, or pivot table, or lookup table, or intermediatory table,<br />

or doing the hibbity-bibbity table. It has a lot of names. The Laravel documentation tends to refer<br />

to them as pivot tables, so I’m going to stick with that. Whenever you need a many_to_many<br />

relationship you will find a need for a pivot table. It’s the database table that links the two entities<br />

together by using two foreign keys to define the rows from the other tables.<br />

Looking at the first two rows of the pivot table, we can see that the user ‘Dayle Rees’ has favourited<br />

both ‘Code Dutch’ and ‘Code Bright’. We can also see that the users Matthew Machuga and Shawn<br />

McCool have both favourited Code Dutch.<br />

There is an additional type of relationship known as a polymorphic relationship. Due to it’s complex<br />

nature, and it’s long name, we will cover it within a later chapter on advanced Eloquent tactics. We<br />

won’t need it yet.<br />

That’s enough learning. It’s time for different learning! Practical learning. Now that we have<br />

discovered the variety of relationships available, let’s learn how to implement them with Eloquent.<br />

Implementing Relationships<br />

Right, let’s set the stage. First we are going to need to construct some tables. Normally I’d create a<br />

new migration for each table, but to simplify the examples I will put them all in one.

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

Saved successfully!

Ooh no, something went wrong!