06.10.2016 Views

laravel-5

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

1 $like = App\Like::find(1);<br />

2<br />

3 $likeable = $like->likeable;<br />

The likeable relation on the Like model will return either a Post or Comment instance, depending<br />

on which type of model owns the like.<br />

Custom Polymorphic Types<br />

By default, Laravel will use the fully qualified class name to store the type of the related model.<br />

For instance, given the example above where a Like may belong to a Post or a Comment, the default<br />

likable_type would be either App\Post or App\Comment, respectively. However, you may wish to<br />

decouple your database from your application’s internal structure. In that case, you may define a<br />

relationship “morph map” to instruct Eloquent to use the table name associated with each model<br />

instead of the class name:<br />

1 use Illuminate\Database\Eloquent\Relations\Relation;<br />

2<br />

3 Relation::morphMap([<br />

4 App\Post::class,<br />

5 App\Comment::class,<br />

6 ]);<br />

Or, you may specify a custom string to associate with each model:<br />

1 use Illuminate\Database\Eloquent\Relations\Relation;<br />

2<br />

3 Relation::morphMap([<br />

4 'posts' => App\Post::class,<br />

5 'likes' => App\Like::class,<br />

6 ]);<br />

You may register the morphMap in the boot function of your AppServiceProvider or create a separate<br />

service provider if you wish.

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

Saved successfully!

Ooh no, something went wrong!