【问题标题】:Laravel API resource whenLoaded not working properly with another valuesLaravel API 资源 whenLoaded 无法与其他值一起正常工作
【发布时间】: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


    【解决方案1】:

    您的第二个参数在发送到函数时被执行。所以解决方案是传递一个可调用对象。

    你必须像这样构造它:

    return [
        'id' => $this->id,
        'name' => $this->name,
        'contacts' => $this->whenLoaded('contacts'),
        'phone' => $this->whenLoaded('contacts', function() {
            return object_get($this->contacts->where('type', 'phone')->first(), 'value');
        })
    ];
    

    我还使用object_get() 进行了一些简化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-21
      • 2020-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多