具有关系的 Laravel 客户 API 资源

Ahm*_*sam 7 laravel laravel-5

控制器功能:

public function index () {
    // TESTED
    // The getAllActiveSuppliers() function just return Supplier::pagniate(10)
    $suppliers = $this -> model -> getAllActiveSuppliers();
    return new SupplierResource($suppliers);
}
Run Code Online (Sandbox Code Playgroud)

返回的Json:

    {
    "current_page": 1,
    "data": [
        {
            "id": 23,
            "name": "Test Name",
            "description": "Test Description",
            "created_by": {
                "id": 1,
                "name": "Test 1",
                "email": "admin@admin.com",
                "email_verified_at": null,
                "active": 1,
                "created_at": "2018-10-12 14:17:38",
                "updated_at": "2018-10-12 14:17:38"
            },
            "updated_by": {
                "id": 1,
                "name": "Test 1",
                "email": "admin@admin.com",
                "email_verified_at": null,
                "active": 1,
                "created_at": "2018-10-12 14:17:38",
                "updated_at": "2018-10-12 14:17:38"
            },
            "deleted_at": null,
            "created_at": "2018-10-31 01:46:11",
            "updated_at": "2018-11-02 22:05:14",

        }
    ],
    ...
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试做的事情:

created_by和updated_by中我只想显示name, email其他内容。

我尝试做的事情:

我尝试创建一个API资源集合

Supply.php API资源集合:

public function toArray($request)
{
    return parent::toArray($request);
}
Run Code Online (Sandbox Code Playgroud)

Tra*_*itz 1

您首先需要为单个JsonResource 对象定义一个结构:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        ...
        'created_by' => $this->created_by->only('name', 'email'),
        ...
    ];
}
Run Code Online (Sandbox Code Playgroud)

然后告诉您的 ResourceCollection 使用该类:

自定义底层资源类

通常, $this->collection资源集合的属性会自动填充集合中每个项目到其单一资源类的映射结果。假定单一资源类是集合的类名,不带尾随Collection 字符串。

例如,UserCollection将尝试将给定的用户实例映射到User资源中。要自定义此行为,您可以覆盖$collects资源集合的属性

(来自https://laravel.com/docs/5.7/eloquent-resources#concept-overview

如果您的 ResourceCollection 不执行任何额外操作,您可能不需要它。每个 JsonResource 都可以使用该方法将自身转换为集合collection(),例如JsonResource::collection($models)