laravel - 优化 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()
但是,这将始终执行关系加载
解决方案
推荐阅读
- python - 为什么 changefeed 发送 JSON 与 Python 解析器不兼容?
- php - 如何触发woocommerce回调函数?
- swift - 为什么我无法访问 .playAndRecord
- android - Kotlin 中 Recycler 视图上方的按钮
- ios - 将生产构建到 AppStore 并收到警告
- javascript - 如何解决:“无法读取 null 的属性 'classList'”?
- javascript - html首先跳转到包含的锚链接url
- apache-kafka - KStream 将记录发送到多个流(不是分支)
- android - 使用 Android App Bundle 时,Crashlytics 不再上传映射文件
- javascript - Vuetify datepicker 没有事件图标和空白字段