带有关系的Laravel客户API资源

时间:2018-11-04 20:27:26

标签: laravel laravel-5

  

控制器功能:

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

退回的杰森:

    {
    "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",

        }
    ],
    ...
}
  

我正在尝试做的事情:

created_by和updated_by 中,我只想显示name, email

  

我试图做的事情:

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

Supplier.php API资源集合:

public function toArray($request)
{
    return parent::toArray($request);
}

2 个答案:

答案 0 :(得分:0)

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

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

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

  

自定义基础资源类

     

通常,   资源集合的$this->collection属性是自动的   将集合的每个项目映射到的结果填充   它的单一资源类。假定单个资源类为   是集合的类名,结尾没有Collection   字符串。

     

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

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

如果您的ResourceCollection不执行任何其他操作,则可能不需要它。每个JsonResource都可以使用collection()方法(例如, JsonResource::collection($models)

答案 1 :(得分:0)

对于在我正在本主题中进行自我搜索时可能仍需要此功能的任何人

首先使用姓名,电子邮件字段为您的关系创建资源

class UserResource extends JsonResource
{

    public function toArray($request)
    {
        return [
            'name' => $this->name,
            'email' => $this->email,
        ];
    }
}

然后创建与用户之间具有created_by关系的SupplierResource

class SupplierResource extends JsonResource
{

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'description' => $this->description,
            'created_by' => new UserResource($this->created_by)
        ];
    }
}

在控制器中

public function index () {

    $suppliers = $this->model->getAllActiveSuppliers();
    
    return SupplierResource::collection($suppliers);
}