如何用Laravel将MySQL数据转换为树形结构JSON文件?
实现步骤
假设你的表名为referrals,按以下步骤完成数据转换:
1. 创建Eloquent模型
先建立对应的数据模型,方便操作数据库:
// app/Models/Referral.php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Referral extends Model { protected $table = 'referrals'; protected $fillable = ['id', 'name', 'reference']; public $timestamps = false; // 表无created_at/updated_at字段时需添加 }
2. 数据格式转换
在控制器或Artisan命令中,通过Laravel集合快速转换字段格式:
use App\Models\Referral; use Illuminate\Support\Facades\Storage; // 获取所有数据 $referrals = Referral::all(); // 映射为目标格式:将reference转为parent,null值替换为0 $formattedData = $referrals->map(function ($item) { return [ 'id' => $item->id, 'name' => $item->name, 'parent' => $item->reference ?? 0, ]; });
3. 生成JSON文件/返回响应
- 若要保存为本地JSON文件:
// 保存到storage/app/referrals.json,JSON_PRETTY_PRINT用于格式化输出 Storage::put('referrals.json', $formattedData->toJson(JSON_PRETTY_PRINT));
- 若要作为接口返回给前端:
return response()->json($formattedData);
补充说明
- 转换逻辑会自动处理
reference为null的情况,将其映射为parent:0,完全匹配你给出的示例格式 - 集合的
map方法遍历效率稳定,适配大数据量场景
内容的提问来源于stack exchange,提问作者hrafn
相关产品推荐
相关产品推荐

