【问题标题】:How can I get tag's post with Eloquent ORM如何使用 Eloquent ORM 获取标签的帖子
【发布时间】:2014-01-09 04:09:44
【问题描述】:

我有适当的基于 ORM 的帖子和标签表。分配给在数据透视表上发布的标签。要在 laravel 中获取帖子->标签,我使用以下模型关系。

//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();

【问题讨论】:

    标签: orm laravel eloquent


    【解决方案1】:

    关系是双向的

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

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

    你可以这样做

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

    【讨论】:

      猜你喜欢
      • 2018-03-26
      • 2013-07-07
      • 1970-01-01
      • 2015-12-27
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      相关资源
      最近更新 更多