首页 > 解决方案 > 优化 ApiResource

问题描述

返回 ApiResources 时我遇到了一些问题,因为我不知道如何避免重载关系。

例如,在我的 UserResource 中,我有:

<?php

return [
    'id' => $this->id,
    'name' => $this->name,
    'email' => $this->email,
    'role_id' => $this->role_id,
    'role' => new RoleResource($this->whenLoaded('role')),
    'group_ids' => $this->groups->pluck('id')->toArray(), // here are the problems
    'groups' => GroupResource::collection($this->whenLoaded('groups')),
];

加载单个关系 id 时,一切正常,因为$this->role_id它是模型中已经存在的属性。使用的时候$this->whenLoaded('role')会有条件地加载关系,太好了!

问题:加载多对多关系时,我无法设置此“条件”急切加载。

当我放置:

'groups' => GroupResource::collection($this->whenLoaded('groups'))

它将有条件地加载多对多关系,酷!

我想有一个 id 数组:

'group_ids' => $this->groups->pluck('id')->toArray()

但是,这将始终执行关系加载

标签: laravelapiresourcesmany-to-manyeager-loading

解决方案


推荐阅读