如何使用Eloquent ORM获取标签的帖子

时间:2014-01-09 04:09:45

标签: orm laravel eloquent

我有适当的基于ORM的帖子和标签表。指定通过数据透视表发布的标记。要在laravel中获取posts->标签,我使用下面的模型关系。

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

这是我的数据库:

post
  id

tags
  id

post_tag
  post_id
  tag_id

问题

我想检索所有具有特定标记名称的帖子。

我尝试了什么

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

此外,我尝试了查询关系,抛出非对象错误。

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

})->get();

1 个答案:

答案 0 :(得分:4)

关系是双向的

您需要定义模型标记 如

class Tag{
    public function posts()
    {
         return $this->belongsToMany('Post');
    }
}
然后你可以做

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