Laravel 5.5 Eloquent WhenLoaded关系

Nuc*_*eus 6 php laravel eloquent

Laravel 5.5文档中,在条件关系下,它说

whenLoaded方法可用于有条件地加载关系

我试过我的代码

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'roles' => Role::collection($this->whenLoaded('roles')),
        'remember_token' => $this->remember_token,
    ];
}
Run Code Online (Sandbox Code Playgroud)

根据文档,在将资源响应发送到客户端之前,完全从资源响应中删除了角色密钥,因为尚未加载该关系.

如何加载关系?如何确定是否加载了关系?在这种情况下,我如何加载Role(模型)?

ker*_*rin 5

渴望加载

雄辩的人可以在查询父模型时“急于加载”关系。

$user = App\User::with('roles')->find($id);
Run Code Online (Sandbox Code Playgroud)

懒惰的渴望加载

在已检索父模型之后急于加载关系

$user->load('roles');
Run Code Online (Sandbox Code Playgroud)

加载缺失关系

在尚未加载关系时加载它

$user->loadMissing('roles');
Run Code Online (Sandbox Code Playgroud)