You need to enable JavaScript to run this app. Laravel 查询构造器如何返回嵌套结构的对象数据
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 查询构造器如何返回嵌套结构的对象数据

需求说明
  • 核心目标:基于Laravel查询构造器的联表查询结果,将扁平字段封装为指定的嵌套对象结构返回
  • 现有输出为单条扁平结构,期望按字段属性拆分为外层公共信息+嵌套明细的结构
  • 原有控制器代码:
$data = DB::table('tr_doctor_schedules as sch')
    ->select('sch.id as schedule_id','doctor_name','hospital_name','estimated_practice_time','day','from_time','until_time')
    ->join('mst_hospitals as hos', 'hos.id', '=', 'sch.hospital_id')
    ->join('mst_doctors as doc', 'doc.id', '=', 'sch.doctor_id')
    ->join('tr_doctor_schedule_details as dtl', 'dtl.doctor_schedule_id', '=', 'sch.id')
    ->where('sch.hospital_id', $hosId)
    ->where('sch.doctor_id', $docId)
    ->first();

if ($data) {
    return response()->json([
        'success' => true,
        'message' =>'success',
        'data'    => $data
    ], 200);
} else {
    return response()->json([
        'success' => false,
        'message' => 'Data not found.',
    ], 400);
}
实现方案

1. 修正查询逻辑

当前代码使用first()只会取联表结果的第一条记录,如果一个日程对应多个出诊时段明细,会直接丢失其他明细数据,需要先将first()改为get(),拿到全量匹配的扁平结果集合。

2. 手动组装嵌套结构

利用查询构造器返回的集合自带方法遍历处理:

  • 取第一条记录的公共字段(schedule_id、doctor_name、hospital_name、estimated_practice_time)作为外层结构
  • 从所有结果中提取明细字段(day、from_time、until_time),组装为嵌套的明细数组

调整后的完整代码

// 替换first()为get(),获取全量联表结果
$collection = DB::table('tr_doctor_schedules as sch')
    ->select('sch.id as schedule_id','doctor_name','hospital_name','estimated_practice_time','day','from_time','until_time')
    ->join('mst_hospitals as hos', 'hos.id', '=', 'sch.hospital_id')
    ->join('mst_doctors as doc', 'doc.id', '=', 'sch.doctor_id')
    ->join('tr_doctor_schedule_details as dtl', 'dtl.doctor_schedule_id', '=', 'sch.id')
    ->where('sch.hospital_id', $hosId)
    ->where('sch.doctor_id', $docId)
    ->get();

if ($collection->isEmpty()) {
    return response()->json([
        'success' => false,
        'message' => 'Data not found.',
    ], 400);
}

// 组装嵌套数据结构
$firstItem = $collection->first();
$nestedData = [
    // 外层公共字段
    'schedule_id' => $firstItem->schedule_id,
    'doctor_name' => $firstItem->doctor_name,
    'hospital_name' => $firstItem->hospital_name,
    'estimated_practice_time' => $firstItem->estimated_practice_time,
    // 嵌套明细数组
    'schedule_details' => $collection->map(function ($item) {
        return [
            'day' => $item->day,
            'from_time' => $item->from_time,
            'until_time' => $item->until_time,
        ];
    })->toArray()
];

return response()->json([
    'success' => true,
    'message' =>'success',
    'data'    => $nestedData
], 200);

补充说明

  • 如果单条日程仅对应单条明细,上述逻辑完全兼容,明细数组只会包含一条数据,也可以直接把明细字段作为外层的子节点手动构造,不需要遍历集合。
  • 不需要依赖Eloquent关联或额外的封装包,所有逻辑基于查询构造器原生返回的集合能力实现,没有额外学习成本。
  • 如果不想用集合的map方法,也可以用原生foreach遍历提取明细字段,效果完全一致:
$details = [];
foreach ($collection as $item) {
    $details[] = [
        'day' => $item->day,
        'from_time' => $item->from_time,
        'until_time' => $item->until_time,
    ];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.28 17:36:06