刚刚迁移到4.1以利用这一强大功能. 在检索单个’morphedByXxxx’关系时,一切似乎都能正常工作,但是当试图检索特定标签所属的所有模型时 – 我得到错误或没有结果. $tag = Tag::find(45); //
在检索单个’morphedByXxxx’关系时,一切似乎都能正常工作,但是当试图检索特定标签所属的所有模型时 – 我得到错误或没有结果.
$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();
我的标签模型类像这样:
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'); } }
Post和Video模型如下所示:
class Post extends Eloquent { protected $table = 'posts'; public $timestamps = true; public function tags() { return $this->morphToMany('Tag', 'taggable'); } }
我能够为帖子和视频添加/删除标签,以及检索任何标签的相关帖子和视频 – 但是 – 检索标签名称为“真棒”的所有模型的正确方法是什么?
能够弄明白,很想听听有关此实施的评论.在Tag.php中
public function taggable() { return $this->morphToMany('Tag', 'taggable', 'taggables', 'tag_id')->orWhereRaw('taggables.taggable_type IS NOT NULL'); }
在调用代码时:
$allItemsHavingThisTag = $tag->taggable() ->with('videos') ->with('posts') ->get();