0

如果我为每个请求创建 API RESOURCES 是否正确。以及如何在资源中的三个表之间建立连接。例如:

class UserResource
public function toArray($request)
{
    return [
       'id'=>$this->id,
       'name'=>$this->name
       'work'=>WorkResource::collection($this->work)//relationship between USER and WORK
    ]
}
class WorkResource
public function toArray($request)
{
    return [
       'id'=>$this->id,
       'title'=>$this->title
    ]
}

在 UserResource 类中,我只需要从没有 ID 的 WORK 中返回 TITLE,我该怎么做?

4

1 回答 1

0

我不确定我是否做对了,但$this->work在您使用Resource::collection(). 所以我的猜测是:

class UserResource
{
    public function toArray($request)
    {
        return [
            'id'   => $this->id,
            'name' => $this->name,
            'work' => new WorkResource($this->whenLoaded('work'))
        ];
    }
}

class WorkResource
{
    public function toArray($request)
    {
        return [
            'title' => $this->title
        ];
    }
}
于 2019-09-25T07:14:08.857 回答