zeu*_*ben 7 polymorphism many-to-many laravel laravel-4
刚刚迁移到4.1以利用这一强大功能.当检索单个'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();
Run Code Online (Sandbox Code Playgroud)
我的标签模型类像这样:
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');
}
}
Run Code Online (Sandbox Code Playgroud)
邮政和视频模型如下所示:
class Post extends Eloquent
{
protected $table = 'posts';
public $timestamps = true;
public function tags()
{
return $this->morphToMany('Tag', 'taggable');
}
}
Run Code Online (Sandbox Code Playgroud)
我能够添加/移除标签的帖子和视频,以及检索相关的帖子和视频的任何标记- 然而 -什么是检索所有型号的正确方法有标签名称"真棒"?
能够弄明白,很想听听有关此实施的评论.
在Tag.php中
public function taggable()
{
return $this->morphToMany('Tag', 'taggable', 'taggables', 'tag_id')->orWhereRaw('taggables.taggable_type IS NOT NULL');
}
Run Code Online (Sandbox Code Playgroud)
在调用代码时:
$allItemsHavingThisTag = $tag->taggable()
->with('videos')
->with('posts')
->get();
Run Code Online (Sandbox Code Playgroud)