Laravel 5.5雄辩的WhenLoaded关系 [英] Laravel 5.5 Eloquent WhenLoaded relationship
问题描述
在条件关系下的 Laravel 5.5文档中. ,它说
whenLoaded方法可用于有条件地加载关系
whenLoaded method may be used to conditionally load a relationship
我尝试使用自己的代码
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,
];
}
根据文档,由于尚未加载关系,因此将角色密钥从资源响应中完全删除之后再发送给客户端.
According to the documentation, the roles key is removed from the resource response entirely before it is sent to the client because the relationship hasn't been loaded.
如何加载关系?如何确定是否加载了关系?在这种情况下,如何加载Role
(模型)?
How do I load a relationship? How do I determine if a relationship is loaded? In this case how do I load Role
(model)?
推荐答案
急切加载
雄辩者可以在查询父模型时急于加载"关系.
Eloquent can "eager load" relationships at the time you query the parent model.
$user = App\User::with('roles')->find($id);
懒惰加载
要在已获取父模型后急于加载关系
To eager load a relationship after the parent model has already been retrieved
$user->load('roles');
加载缺少的关系
仅在尚未加载关系时加载
To load a relationship only when it has not already been loaded
$user->loadMissing('roles');
这篇关于Laravel 5.5雄辩的WhenLoaded关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!