我想获得帖子的标签.
这是我的数据库与数据透视表
post body tag name post_tag post_id tag_id
到目前为止,我可以看到并能够理解hasManyThrough()
这一点.但是我在我的Post
模型中调用了tags()
return $this->hasManyThrough('Post', 'Tag', 'post_id', 'tag_id');
不起作用.
不.您展示的是ManyToMany关系:http: //laravel.com/docs/eloquent#relationships
你要做的就是这样(在Post模型中):
return $this->belongsToMany('Tag', 'post_tag', 'post_id', 'tag_id');
这种hasManyThrough
关系意味着一种捷径.鉴于此模型:
user name post user_id body tag name post_tag post_id tag_id
当你想要查看用户的所有标签(给定用户是许多帖子的所有者)时它会派上用场,所以你会做这样的事情(在用户模型中):
return $this->hasManyThrough('Post', 'Tag', 'post_id', 'tag_id');
希望这对你有所帮助!