2014-01-09 34 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;