繁体   English   中英

laravel 5.6-获取多个属于多个子级的父子数据

[英]laravel 5.6 - get data of multiple layers of parent-child with belongs to many

想象一下,我有一个站点,里面有很多catalogs ,每个catalogs都有多个sections ,每个section都有items

  • catalogsbelongstomanysections
  • sectionsbelongstomanyitems

我想要的最终结果是要有一个嵌套数据:

{
  "catalog_id": 1,
  "catalog_name": "catalog 01",
  "sections": [
    {
      "section_id": 1,
      "name": "section 01",
      "items": [
        {
          "item_id": 1,
          "item_content": {
            "name": "some content1"
          }
        },
        {
          "item_id": 2,
          "item_content": {
            "name": "some content2"
          }
        },
        {
          "item_id": 3,
          "item_content": {
            "name": "some content3"
          }
        }
      ]
    },
    {
      "section_id": 2,
      "name": "section 02",
      "items": [
        {
          "item_id": 2,
          "item_content": {
            "name": "some content2"
          }
        },
        {
          "item_id": 3,
          "item_content": {
            "name": "some content3"
          }
        },
        {
          "item_id": 4,
          "item_content": {
            "name": "some content4"
          }
        }
      ]
    }
  ]
}

我该如何实现?

从技术上讲,我可以使用each-loop获取所需的内容,但我希望这是Eloquent更好的解决方案。

尝试这个

Catalogs::with('sections.items')->get();

我会在@ J.Doe回答中添加您可以指定要执行的操作。 例如

Catalogs::with([
   'sections' => function($query){
       return $query->select('column')
              ->where('someCondition', 1)
              ->orderBy('id', 'asc');
   'items' => //some other stuff
];

您还可以将方法with()用于您的关系。 可以说与someTable相关的sections 如果section模型中有关联方法someTable ,则:

Catalogs::with([
   'sections' => function($query){
       return $query->select('column')
              ->with('someTable') // here's your relation 
              ->where('someCondition', 1)
              ->orderBy('id', 'asc');
   'items' => //some other stuff
];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM