【问题标题】:Laravel Error when referencing a resource in a resource引用资源中的资源时 Laravel 错误
【发布时间】:2019-08-04 06:08:04
【问题描述】:

我在控制器中使用了 Laravel Json 资源,如下

public function index(Request $request)
{
    $itemsWithTranslations = MenuItem::where(['menu_id' => $request->id, 'parent_id' => null])
        ->with(['children', 'translations'])
        ->orderBy('sort_order', 'asc')
        ->get();

    return MenuItemResource::collection($itemsWithTranslations);
}

现在我想在这个集合中生成一个集合,其中包含正在显示的项目的子项。

以下代码可以正常工作。 注意我是如何注释掉儿童参考的

class MenuItemResource extends JsonResource
{

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'text' => $this->title,
            // 'children' => MenuItemResource::collection($this->whenLoaded('children')),
            'data' => [
                'id' => [
                    'value' => $this->id,
                    'type' => 'hidden'
                ],
                'title' => [
                    'value' => $this->title,
                    'type' => 'text',
                    'label' => 'Title'
                ],
                'resource_link' => [
                    'value' => $this->resource_link,
                    'type' => 'text',
                    'label' => 'Resource Link'
                ],
                'translations' => MenuItemTranslationResource::collection($this->whenLoaded('translations'))->keyBy(function ($translation) {
                    return $translation['locale'];
                })
            ]
        ];
    }
}

当我取消注释孩子时,我收到以下错误

"调用未定义的方法 Illuminate\Http\Resources\Json\AnonymousResourceCollection::keyBy()"

在资源中包含资源是错误的吗?或者我应该怎么做?

型号

class MenuItem extends Model
{
    protected $table = 'menu_items';
    protected $fillable = ['menu_id', 'parent_id', 'title', 'order', 'resource_link', 'html_class', 'is_blank'];

    public function translations()
    {
        return $this->hasMany(MenuItemTranslation::class, 'menu_item_id');
    }

    public function children()
    {
        return $this->hasMany(MenuItem::class, 'parent_id');
    }
}

额外信息

当我返回以下数据时,它确实返回空作为孩子的集合。

MenuItemResource::collection($this->children);

返回

如果我返回没有集合的孩子,它会返回它们(对于 1 项,这是正确的)

return $this->children;

返回

【问题讨论】:

  • 不,我们可以在其他资源中使用资源。
  • 你能在“MenuItem”模型中显示你的模型与“children”的关系吗
  • 添加到问题中,谢谢。

标签: php laravel


【解决方案1】:

你应该使用 ChildrenResource::collection

'children' => ChildrenResource::collection($this->whenLoaded('children'))

希望这行得通。

如果不存在,则创建一个 ChildrenResource 类。

【讨论】:

  • 这是一个自引用表,正如您在模型中看到的,所以它的布局基本相同。我还为问题添加了更多信息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-04
  • 2018-04-05
  • 2019-12-04
相关资源
最近更新 更多