-
Forked from
ctf0 -
https://laravel.com/docs/master/eloquent-relationships#many-to-many-polymorphic-relations except
Defining The Inverse Of The Relationship, instead we will use the below -
Defining the inverse typically requires multiple
morphedByManydefinitions, and then a merge if you want to achieve what we're doing here -
thanx to setup oneToMany relation between
tag & taggable
This creates creates a morphPivot that does the relationship work to allow us to pull the related models from the morphTo model. Using groupby keeps the DB queries as efficient as possible
NOTE: the dual use of
Taggablefor the trait and themorphPivotmight be confusing, consider usingApp\Models\TaggableMorphas the actual pivot model name.
Models:
App\Models\Tag;
App\Models\Taggable;
App\Concerns\Taggable as TaggableMorph;
App\Models\AnyTaggableModel; // any model that can be taggedUsage
AnyTaggableModel::first()->related_models;