php - Laravel 资源 whenLoaded hasManyTrough 关系
问题描述
我正在尝试使用基于 hasManyThrough 关系的第二个资源来构建资源集合。当我调用主要资源上的实际关系时,它确实为我提供了正确的数据。每当我将数据传递给另一个资源并使用 whenLoaded() 方法时,它不会将数据链接到主集合。
该模型:
public function fields()
{
return $this->hasManyThrough(Field::class, FieldValue::class, 'component_id', 'id', 'id', 'field_id');
}
控制器:
/**
* @return JsonResponse
*/
public function index()
{
$components = Component::with(['fields'])->get();
return ComponentValueResource::collection($components)->response();
}
组件值资源类:
public function toArray($request)
{
return [
'fields' => FieldResource::collection($this->whenLoaded('fields')),
];
}
字段资源类:
public function toArray($request)
{
$fields = $this->whenLoaded('fields');
return [
'fields' => new ComponentValueResource($fields),
];
}
的输出dd(FieldResource::collection($this->whenLoaded('fields')));
#original: array:9 [
"id" => 1
"base_id" => 1
"component_id" => null
"identifier" => "text input"
"type" => "text"
"position" => 1
"created_at" => "2021-08-22 19:44:23"
"updated_at" => "2021-08-22 19:44:23"
"laravel_through_key" => 6
]
资源的输出:
{
"data": [
{
"id": 6,
"fields": [
[]
]
},
解决方案
推荐阅读
- c++ - C++ 模板类的内部类访问
- dictionary - 是否可以在颤动的折线上添加箭头?
- javascript - 为什么此代码出现错误“嗨不是函数”
- mysql - MySQL 数据目录在 docker 镜像中使用 -v 标志保持默认
- javascript - 对字符串文字类的 DOM 操作
- android - 用于存储 3D 模型的 AR 应用程序数据库
- javascript - 对不同的 html li 对象使用相同的 jquery 函数
- reactjs - 如何获取 js-cookies?
- ios - 如何使用 xcode(swift 5)上的 healthkit 从健康中读取跟踪周期数据(周期预测日期)?
- r - 如何将不同级别信息的数据转换成宽格式?