首页 > 解决方案 > 将用户对象绑定到 laravel 中的每篇文章

问题描述

这是在这个例子中我获取所有category拥有的articles 并将所有文章绑定到每个category属于这样的文章

 $categories = Category::has('articles')->with('articles')->get();

结果

   [
{
    "id": 1,
    "title": "Technology",
    "created_at": "2019-09-22 16:58:24",
    "updated_at": "2019-09-22 16:58:24",
    "articles": []
  },
  {
    "id": 2,
    "title": "Programming",
    "created_at": "2019-09-22 21:01:39",
    "updated_at": "2019-09-22 22:36:17",
    "articles": [{
      "id": 10,
      "title": "Intro To JavaScript",
      "content": "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
      "image": "articles/OUMvOY17KaqfcfK10c16UAcGegXeESopRw1hlxl9.png",
      "user_id": 1,
      "category_id": 2,
      "created_at": "2019-09-22 22:35:10",
      "updated_at": "2019-09-22 22:35:10"
    }]
  }
]

我需要的是也user为每个对象绑定article我该怎么做

标签: phplaraveleloquentrelational-database

解决方案


也许这可以帮助你:

 $categories = Category::has('articles')->with('articles' => function($query) {
    $query->with('user');
})->get();

希望能帮助到你。


推荐阅读