06.10.2016 Views

laravel-5

Create successful ePaper yourself

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

Eloquent: Relationships 590<br />

Many To Many Polymorphic Relations<br />

Table Structure<br />

In addition to traditional polymorphic relations, you may also define “many-to-many” polymorphic<br />

relations. For example, a blog Post and Video model could share a polymorphic relation to a Tag<br />

model. Using a many-to-many polymorphic relation allows you to have a single list of unique tags<br />

that are shared across blog posts and videos. First, let’s examine the table structure:<br />

1 posts<br />

2 id - integer<br />

3 name - string<br />

4<br />

5 videos<br />

6 id - integer<br />

7 name - string<br />

8<br />

9 tags<br />

10 id - integer<br />

11 name - string<br />

12<br />

13 taggables<br />

14 tag_id - integer<br />

15 taggable_id - integer<br />

16 taggable_type - string<br />

Model Structure<br />

Next, we’re ready to define the relationships on the model. The Post and Video models will both<br />

have a tags method that calls the morphToMany method on the base Eloquent class:<br />

1

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

Saved successfully!

Ooh no, something went wrong!