29.07.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 456<br />

Typical Eloquent foreign key conventions will be used when performing the relationship’s queries. If<br />

you would like to customize the keys of the relationship, you may pass them as the third and fourth<br />

arguments to the hasManyThrough method. The third argument is the name of the foreign key on the<br />

intermediate model, while the fourth argument is the name of the foreign key on the final model.<br />

.<br />

1 class Country extends Model<br />

2 {<br />

3 public function posts()<br />

4 {<br />

5 return $this->hasManyThrough('App\Post', 'App\User', 'country_id', 'user\<br />

6 _id');<br />

7 }<br />

8 }<br />

Polymorphic Relations<br />

Table Structure<br />

Polymorphic relations allow a model to belong to more than one other model on a single association.<br />

For example, imagine you want to store photos for your staff members and for your products. Using<br />

polymorphic relationships, you can use a single photos table for both of these scenarios. First, let’s<br />

examine the table structure required to build this relationship:<br />

.<br />

1 staff<br />

2 id - integer<br />

3 name - string<br />

4<br />

5 products<br />

6 id - integer<br />

7 price - integer<br />

8<br />

9 photos<br />

10 id - integer<br />

11 path - string<br />

12 imageable_id - integer<br />

13 imageable_type - string<br />

Two important columns to note are the imageable_id and imageable_type columns on the photos<br />

table. The imageable_id column will contain the ID value of the owning staff or product, while

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

Saved successfully!

Ooh no, something went wrong!