You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel API开发:如何将children嵌套进data对象返回JSON?

Laravel API CMS 响应结构修正

期望的JSON响应结构

{
  "data": {
    "id": 1,
    "slug": "",
    "title": "first",
    "description": "This is the complete body for the CMS page",
    "parentPageId": 0,
    "image": "",
    "metaDescription": "meta ",
    "created_at": null,
    "updated_at": null,
    "creatorID": null,
    "isActive": 0,
    "children": [
        {
          "title": "first",
          "description": "This is the complete body for the CMS page",
          "image": ""
        }
    ]
  }
}

当前实际返回的JSON结构

{
  "data": {
    "id": 1,
    "slug": "",
    "title": "first",
    "description": "This is the complete body for the CMS page",
    "parentPageId": 0,
    "image": "",
    "metaDescription": "meta ",
    "created_at": null,
    "updated_at": null,
    "creatorID": null,
    "isActive": 0
  },
  "children": [
    {
      "title": "first",
      "description": "This is the complete body for the CMS page",
      "image": ""
    }
  ]
}

现有控制器代码

public function show($slug)
{
    try {
        $data = Page::where('slug', $slug)->orWhere('id', $slug)->firstOrFail();
        $sub = Page::select('title', 'description', 'image')->where('parentPageId', $data->id)->get();
        return['data'=>$data, 'children' => $sub];
    } catch (Exception $e) {
        return $this->returnJson(false, $e->getMessage(), $e->getCode());
    }
}

修正方案

方案一:直接为模型实例附加属性

将查询到的子页面集合添加到主页面模型实例中,再将主页面作为data的值返回:

public function show($slug)
{
    try {
        $page = Page::where('slug', $slug)->orWhere('id', $slug)->firstOrFail();
        $children = Page::select('title', 'description', 'image')->where('parentPageId', $page->id)->get();
        
        // 为模型实例添加children属性
        $page->children = $children;
        
        return ['data' => $page];
    } catch (Exception $e) {
        return $this->returnJson(false, $e->getMessage(), $e->getCode());
    }
}

方案二:使用Eloquent关联(推荐)

这种方式更符合Laravel设计思想,便于后续复用关联逻辑:

  1. 在Page模型中定义子页面关联:
// app/Models/Page.php
public function children()
{
    return $this->hasMany(Page::class, 'parentPageId', 'id')
                ->select('title', 'description', 'image');
}
  1. 修改控制器代码,使用预加载获取关联数据:
public function show($slug)
{
    try {
        $page = Page::with('children')
                    ->where('slug', $slug)
                    ->orWhere('id', $slug)
                    ->firstOrFail();
        
        return ['data' => $page];
    } catch (Exception $e) {
        return $this->returnJson(false, $e->getMessage(), $e->getCode());
    }
}

两种方案都能让children嵌套在data对象内部,符合期望的JSON结构。


内容的提问来源于stack exchange,提问作者Abhishek Regmi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 07:45:25