Laravel 在 JSONresource 中加载 JSONresource(父 -> 子 [hasMany] 关系)



我们有两个对象。业务和服务。一个企业可以有多种服务。当我们获取业务时,我希望它在响应中包含服务。关系设置正确,BusinessResource具有正确的数据。

class Business extends JsonResource {
public function toArray($request)
{
return [
'uuid'          => $this->uuid,
'account_uuid'  => $this->account_uuid,
'gid'           => $this->gid,
'gid_short'     => $this->gid_short,
'name'          => $this->name,
'type'          => $this->type,
'default_locale'    => $this->default_locale,
'default_currency'  => $this->default_currency,
'services'          => $this->services, //Loads the services straight from the DB
'logo'              => $this->logo,
];
}
}

现在,我们希望在它们自己的资源中格式化服务。

类服务扩展JsonResource{

public function toArray($request)
{
return [
'uuid'                  => $this->uuid,
'business_id'           => $this->business_uuid,
'key'                   => $this->key,
'value'                 => $this->value,
'title'                 => TranslationsHelper::getTranslation(config('translatable.locale'), $this->key),
'type'                  => $this->type,
'frontend_adjustable'   => $this->frontend_adjustable,
'created_at'            => $this->created_at,
'updated_at'            => $this->updated_at,
];
}

我试过以下几种。

'services'          => ServiceCollection::collection($this->services), 

这引发了一个错误:

Call to undefined method AppModelsBusinessService::mapInto() {"exception":"[object] (BadMethodCallException(code: 0): Call to undefined method App\ModelsBusinessService::mapInto() at  App/Services/businesses/vendor/illuminate/support/Traits/ForwardsCalls.php:71)

所以现在我的问题是。。如何在父资源中包含ResourceCollection?

在Laravel 8.x中,您应该能够执行Service::make($this->services(,但这会引发一个错误:(Exception(code: 0): Property [uuid] does not exist on this collection instance.是的,UUID确实存在于该属性上。

找到了!

'services'          => ServiceResource::collection($this->services)

最新更新