我创建了一个UserResource
成功返回所有用户属性的方法,包括它所属的组织。它看起来像这样:
资源/User.php
return [
'type' => 'users',
'id' => (string)$this->id,
'attributes' => [
'name' => $this->name,
'email' => $this->email,
...
'relationships' => [
'organization' => $this->organization,
],
];
在我的User
模型中,有一个belongsTo
关系User->Organization
。
我不想返回实际的组织模型,而是返回组织资源。
例如,组织hasMany
位置:
资源/组织.php
return [
'type' => 'organizations',
'id' => (string)$this->id,
'attributes' => [
'name' => $this->name,
...
'relationships' => [
'locations' => Location::collection($this->locations),
],
];
我可以成功返回属于该组织的位置集合。我无法恢复belongsTo
关系。
我试过了:
资源/User.php
'relationships' => [
'organization' => Organization::collection($this->organization),
],
// or this
'relationships' => [
'organization' => Organization::class($this->organization),
],
// or this
use App\Http\Resources\Organization as OrganizationResource;
...
'relationships' => [
'organization' => OrganizationResource($this->organization),
],
如何将单个模型作为相关资源返回?感谢您的任何建议!