2014-01-09 36 views
0

我有适当的基于ORM的帖子和标签表。通过数据透视表发布标签。要在laravel中获得posts->标签,我使用下面的模型关系。我怎样才能得到标签的帖子与雄辩ORM

//Model: Post 
public function tags() 
{ 
$this->belongsToMany('Tag', 'post_tag', 'post_id', 'tag_id'); 
} 

这里是我的数据库:

post 
    id 

tags 
    id 

post_tag 
    post_id 
    tag_id 

问题

我想要检索具有spesific标记名称的所有帖子。

我试过

Post::with(array('tags' => function($query) { $query->where('id', '=', 44); }))->get();与预先加载。但给了完整性错误。

另外我试过查询关系,抛出非对象错误。

Post::whereHas('tags', function($q) 
{ 
    $q->where('id', '=', $tag_id); 

})->get(); 

回答

4

的关系是双向的

你需要定义你的模型标记 作为

class Tag{ 
    public function posts() 
    { 
     return $this->belongsToMany('Post'); 
    } 
} 

,你可以再做

$posts = Tag::find(44)->posts;