【问题标题】:How to get the child data along with the parent writer data in laravel eloquent?如何在 laravel eloquent 中获取子数据和父作者数据?
【发布时间】:2020-01-21 04:50:54
【问题描述】:

我有四张桌子,

      user              writer            blog                                    likes

   id   name          id   name         id   writer_id  content                 user_id    blog_id
   1     aa            1    cc          1       1        lorem                     1          2
   2     bb            2    dd          2       1        lorem ipsum               1          3  
                                        3       2        lorem ipsum               2          2

我拥有user id = 2,现在我必须获得blog writer data。我需要结果是这种形式,

data: {
  'blog': {
      'id':2,
      'writer_id': 1,
      'content': 'lorem ipsum'
  },
  'writer':{
      'id':2,
      'name':'dd'
  }
}

我在likes model 中写了这个关系,但它对我不起作用。

public function writer()
    {
        return $this->hasManyThrough('App\Writer', 'App\Blog', 'writer_id', 'id', 'id', 'id');
    }

如何编写一个雄辩的关系来显示上面的数据?

【问题讨论】:

标签: laravel eloquent relationship


【解决方案1】:

我稍微修改了我的关系,它对我有用

  public function writer()
        {
            return $this->hasManyThrough('App\Writer', 'App\Blog', 'id', 'id', 'blog_id', 'id');
        }

这里的关系中,前两个参数分别表示模型和third parameter id indicates id in the blog tablefourth id indicates the id in writer table

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多