Retrieving all morphedByMany relations in Laravel Eloquent
Did you think to use the "union" function of the collections to merge all the different collection in order to retrieve all what you need?
class Tag extends Model
{
[...]
/**
* Get all of.
*/
public function morphed()
{
return $this->video->union($this->posts)->all();
}
}
I use a trick here:
Create a Model Taggable
for your connection table taggable
and add a hasMany
relation to the Tag
model.
public function related()
{
return $this->hasMany(Taggable::class);
}
Within your Taggable
model create a morphedTo
relation.
public function taggables()
{
return $this->morphTo();
}
Now you can get all models which are using the tag by calling:
$tagged = Tag::with('related.taggables');