Laravel 4.1: the right way to get all morphedBy relationships?

Just switched to 4.1 to take advantage of this powerful feature. everything seems to work correctly when getting the individual morphedByXxxx relationship, however when I try to get all the models to which a particular tag belongs, I get an error message or no results.

$tag = Tag::find(45); //Tag model name = 'awesome' //returns an Illuminate\Database\Eloquent\Collection of zero length $tag->taggable; //returns Illuminate\Database\Eloquent\Relations\MorphToMany Builder class $tag->taggable(); //returns a populated Collection of Video models $tag->videos()->get(); //returns a populated Collection of Post models $tag->posts()->get(); 

My Model Model class looks like this:

 class Tag extends Eloquent { protected $table = 'tags'; public $timestamps = true; public function taggable() { //none of these seem to function as expected, //both return an instance of MorphToMany //return $this->morphedByMany('Tag', 'taggable'); return $this->morphToMany('Tag', 'taggable'); //this throws an error about missing argument 1 //return $this->morphToMany(); } public function posts() { return $this->morphedByMany('Post', 'taggable'); } public function videos() { return $this->morphedByMany('Video', 'taggable'); } } 

And the Post and Video models look like this:

 class Post extends Eloquent { protected $table = 'posts'; public $timestamps = true; public function tags() { return $this->morphToMany('Tag', 'taggable'); } } 

I can add / remove tags in messages and videos, and also get related messages and videos for any tag - however, what is the right way to get all models that have the tag name 'awesome'?

+7
polymorphism laravel laravel-4 many-to-many
source share
2 answers

I was able to understand this, I would like to hear comments on this implementation.

in tag.php

 public function taggable() { return $this->morphToMany('Tag', 'taggable', 'taggables', 'tag_id')->orWhereRaw('taggables.taggable_type IS NOT NULL'); } 

when calling the code:

 $allItemsHavingThisTag = $tag->taggable() ->with('videos') ->with('posts') ->get(); 
+6
source share

I just used this on Laravel 5.2 (not sure if this is a good strategy):

Tag Model:

 public function related() { return $this->hasMany(Taggable::class, 'tag_id'); } 

Taggable model:

 public function model() { return $this->belongsTo( $this->taggable_type, 'taggable_id'); } 

To get all the inverse relationships (all entities attached to the requested tag):

 @foreach ($tag->related as $related) {{ $related->model }} @endforeach 

... Unfortunately, this method does not offer active boot functions and feels like a hack. At the very least, this simplifies the verification of the corresponding model class and shows the desired attributes of the model without much fear of finding the right attributes on the right model.

I sent a similar question to this other thread , as I am looking for relationships unknown in advance.

0
source share

All Articles