阅读(388) (2)

Laravel 8 关联

2021-07-08 09:45:04 更新

如果你希望在响应中包含关联资源,你只需要将它们添加到 toArray 方法返回的数组中。在下面这个例子里,我们将使用 Post 资源的 collection 方法将用户的文章添加到资源响应中:

/**
 * 将资源转换成数组。
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'posts' => PostResource::collection($this->posts),
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
    ];
}

{提示} 如果你只想在关联已经加载时才添加关联资源,请查看文档 条件关联