-
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
morphedByMany
definitions, 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
Taggable
for the trait and themorphPivot
might be confusing, consider usingApp\Models\TaggableMorph
as 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 tagged
Usage
AnyTaggableModel::first()->related_models;