【发布时间】:2020-11-15 01:56:24
【问题描述】:
代码如下:
class Profile extends JsonResource
{
public function toArray($request)
{
return [
'data' => [
'type' => 'profiles',
'profile_id' => $this->id,
'attributes' => [
'avatar' => $this->avatar,
'gender' => $this->gender,
'observers' => new ProfileCollection(\App\Profile::whereIn('user_id', $this->observers->pluck('id'))->get()),
'observing' => new ProfileCollection($this->user->observing),
'birthday' => optional($this->birthday)->format('m/d/Y'),
'address' => $this->address,
'friendship' => new FriendResource(Friend::friendship($this->user->id)),
]
],
'links' => [
'self' => url('/profiles/' . $this->id)
]
];
}
}
观察者和观察中的问题。当我同时使用这两个属性时,我得到错误: 超出最大堆栈深度
当我关闭其中一个时,一切都很好。这个 Profile 类是 - 资源,所以我调用了观察者并观察了这个资源的集合。
我不明白在这种情况下如何增加 json 的深度? 谢谢。
【问题讨论】:
-
可以分享一下用户模型吗?
-
公共函数observing() { return $this->belongsToMany(Profile::class, 'observers', 'user_id', 'profile_id') ->withTimestamps(); }
-
我认为是因为递归调用配置文件资源一次又一次。我会改变它并从另一个资源中调用它)
-
只是不要调用ProfileResource中的任何资源,为什么不遍历
$this->observers,根据需求创建一个数组,然后在返回数组中添加到这里。 -
我通过创建另一个模型资源来解决这个问题,它是配置文件的层次父级 - 它的 UserResource。所以我可以在其中包含 Profile。问题是因为我在另一个 ProfileCollection 中调用 ProfileCollection 的次数不受限制。因此我的资源构造不好
标签: json laravel laravel-collection