ala*_*yli 2 laravel eloquent laravel-4
我想获得帖子的标签.
这是我的数据库与数据透视表
post
body
tag
name
post_tag
post_id
tag_id
Run Code Online (Sandbox Code Playgroud)
到目前为止,我可以看到并能够理解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');
Run Code Online (Sandbox Code Playgroud)
这种hasManyThrough关系意味着一种捷径.鉴于此模型:
user
name
post
user_id
body
tag
name
post_tag
post_id
tag_id
Run Code Online (Sandbox Code Playgroud)
当你想要查看用户的所有标签(给定用户是许多帖子的所有者)时它会派上用场,所以你会做这样的事情(在用户模型中):
return $this->hasManyThrough('Post', 'Tag', 'post_id', 'tag_id');
Run Code Online (Sandbox Code Playgroud)
希望这对你有所帮助!
| 归档时间: |
|
| 查看次数: |
2158 次 |
| 最近记录: |