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

Laravel Orion中API Resources不显示environment关联字段怎么办?

问题:Laravel Orion接口无法返回Post模型的environment关联信息

我正在使用Laravel Orion,希望在接口返回中展示Post模型的environment关联信息,相关代码如下:

PostsController

<?php

namespace App\Http\Controllers\API\V1;

use App\Models\User;
use Orion\Http\Controllers\RelationController;

class PostsController extends RelationController
{
    protected $model = User::class;

    protected $relation = 'posts';

    public function filterableBy(): array
    {
        return ['environment.type'];
    }

    public function includes(): array
    {
        return ['user', 'environment'];
    }
}

PostResource

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{ 
    public function toArray($request)
    {
        return parent::toArray($request) + [
            'environment' => new EnvironmentResource($this->whenLoaded('environment'))
        ];
    }
}

App/Models/Post

<?php 
class Post extends Model
{   
    public function environment(): BelongsTo
    {
        return $this->belongsTo(Environment::class);
    }
}

当前接口响应如下:

{
    "data": [
        {
            "id": "..",
            "title": "..",
            "body": "...",
            ....        
        }
]
}

我希望加载environment信息,但响应中未显示environment字段,请问该如何解决?


解决方法

1. 指定资源映射类

在PostsController中添加$resource属性,明确告诉Orion使用你的自定义PostResource序列化Post模型:

protected $resource = \App\Http\Resources\PostResource::class;

如果不指定,Orion会使用默认资源类,不会包含你自定义添加的environment字段。

2. 强制默认预加载关联

Orion默认需要通过请求参数?include=environment触发关联加载,若想无需参数自动加载,在控制器中添加$alwaysIncludes属性:

protected $alwaysIncludes = ['environment'];

3. 验证关联预加载逻辑

检查Post模型的关联定义,可添加withDefault()确保空关联时字段仍返回默认结构:

public function environment(): BelongsTo
{
    return $this->belongsTo(Environment::class)->withDefault();
}

4. 调整资源序列化逻辑

避免依赖父类toArray的不确定行为,直接在PostResource中明确返回所需字段:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'title' => $this->title,
        'body' => $this->body,
        'environment' => new EnvironmentResource($this->whenLoaded('environment'))
    ];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 13:29:51