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

Laravel自定义API Resource如何实现与原生join查询一致的返回结果

步骤1:创建单个用户资源类

执行命令生成资源文件:
php artisan make:resource UserResource
编辑app/Http/Resources/UserResource.php的toArray方法,完全匹配你需要的返回字段结构:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'username' => $this->username,
        'status' => $this->status,
        'id_cost_center' => $this->id_cost_center,
        'code_cost_center' => $this->cost_center->code,
        'cost_center' => $this->cost_center->description,
        'id_dependence' => $this->id_dependence,
        'dependence' => $this->dependence->description,
        'id_profile' => $this->id_profile,
        'profile' => $this->profile->name,
        'created_at' => $this->created_at
    ];
}

步骤2:修改控制器逻辑

你可以选择替换原有join查询为更简洁的关联预加载写法,性能和原写法接近:

public function index()
{
    // 预加载关联避免N+1查询
    $users = User::with(['cost_center', 'dependence', 'profile'])
                ->orderBy('created_at', 'desc')
                ->get();

    // 直接将资源集合传入sendResponse
    $message = $this->sendResponse(\App\Http\Resources\UserResource::collection($users), 'List of users');

    return $message;
}

如果你不想修改原有的join查询也可以直接使用,只需调整UserResource的取值方式,直接取join查询生成的属性即可:

// 适配原join查询的UserResource写法
public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'username' => $this->username,
        'status' => $this->status,
        'id_cost_center' => $this->id_cost_center,
        'code_cost_center' => $this->code_cost_center,
        'cost_center' => $this->cost_center,
        'id_dependence' => $this->id_dependence,
        'dependence' => $this->dependence,
        'id_profile' => $this->id_profile,
        'profile' => $this->profile,
        'created_at' => $this->created_at
    ];
}

可选:自定义集合资源适配

如果你需要保留自定义的用户集合类,修改集合类的toArray方法如下:

public function toArray($request)
{
    return \App\Http\Resources\UserResource::collection($this->collection);
}

控制器调用时直接传入集合实例即可:

$message = $this->sendResponse(new \App\Http\Resources\UserCollection($users), 'List of users');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:15:03