【发布时间】:2020-09-11 22:40:20
【问题描述】:
我正在使用 API 资源,但我想添加一些额外的逻辑。 我有这个资源:
return [
'id' => $this->id,
'name' => $this->name,
'contacts' => $this->whenLoaded('contacts'),
'phone' => $this->whenLoaded('contacts',
$this->contacts->where('type', '=', 'phone')->first()
? $this->contacts->where('type', '=', 'phone')->first()->value
: null),
];
contacts 是一种“一对多”关系,有多种联系方式(电话、电子邮件等)。
然后我想添加属性“电话”,它将返回电话联系人。
此代码工作正常,问题是即使未加载“联系人”关系,也始终加载属性电话,这对性能非常不利,因为当我不需要时正在做 N+1 问题电话属性。
我是否使用了错误的 whenLoaded 方法?逻辑很简单,在加载联系人关系时获取电话属性,否则不要这样做。
【问题讨论】:
标签: laravel eloquent relationship eager-loading