【问题标题】:Maximum stack depth exceeded Laravel Collection Resource超过最大堆栈深度 Laravel 集合资源
【发布时间】: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


【解决方案1】:

它们必须是您检索数据的方式中的一个循环,可能在用户观察中存在一个用户配置文件,该用户配置文件将再次寻找一个用户观察,该用户观察将查找用户配置文件等等

【讨论】:

    猜你喜欢
    • 2021-11-21
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 2020-01-05
    • 2020-08-10
    • 1970-01-01
    相关资源
    最近更新 更多