1

我创建了一个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),
],

如何将单个模型作为相关资源返回?感谢您的任何建议!

4

1 回答 1

1

你试过用new关键字吗?

'relationships' => [
    'organization' => new OrganizationResource($this->organization),
],
于 2020-05-30T15:15:49.213 回答