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'?
polymorphism laravel laravel-4 many-to-many
zeuben
source share