如何为 belongsTo 创建 Laravel 资源关系?
How can I create a Laravel Resource relationship for a belongsTo?
我创建了一个 UserResource
,它成功地 returning 我的所有用户属性,包括它所属的组织。它看起来像这样:
Resources/User.php
return [
'type' => 'users',
'id' => (string)$this->id,
'attributes' => [
'name' => $this->name,
'email' => $this->email,
...
'relationships' => [
'organization' => $this->organization,
],
];
在我的 User
模型中,User->Organization
有一个 belongsTo
关系。
我不想 return 实际的组织模型,而是 return 组织资源。
例如,组织 hasMany
个地点:
Resources/Organization.php
return [
'type' => 'organizations',
'id' => (string)$this->id,
'attributes' => [
'name' => $this->name,
...
'relationships' => [
'locations' => Location::collection($this->locations),
],
];
我可以成功 return 属于组织的位置集合。我无法 return 建立 belongsTo
关系。
我试过:
Resources/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),
],
如何 return 将单个模型作为相关资源?感谢您的任何建议!
你用 new
关键字试过吗?
'relationships' => [
'organization' => new OrganizationResource($this->organization),
],
我创建了一个 UserResource
,它成功地 returning 我的所有用户属性,包括它所属的组织。它看起来像这样:
Resources/User.php
return [
'type' => 'users',
'id' => (string)$this->id,
'attributes' => [
'name' => $this->name,
'email' => $this->email,
...
'relationships' => [
'organization' => $this->organization,
],
];
在我的 User
模型中,User->Organization
有一个 belongsTo
关系。
我不想 return 实际的组织模型,而是 return 组织资源。
例如,组织 hasMany
个地点:
Resources/Organization.php
return [
'type' => 'organizations',
'id' => (string)$this->id,
'attributes' => [
'name' => $this->name,
...
'relationships' => [
'locations' => Location::collection($this->locations),
],
];
我可以成功 return 属于组织的位置集合。我无法 return 建立 belongsTo
关系。
我试过:
Resources/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),
],
如何 return 将单个模型作为相关资源?感谢您的任何建议!
你用 new
关键字试过吗?
'relationships' => [
'organization' => new OrganizationResource($this->organization),
],