laravel - 向 Laravel 集合添加新属性
问题描述
我访问了几个这样的集合,
$articleActions = EloArticleReferenceAction
::where('file', '=', $file)
->get()
->keyBy('type');
$referencesWithValidDois = EloDoi
::where('file', '=', $file)
->get();
我想合并它们。我不能使用merge
,因为两个对象中的某些 ID 相似,因此一个会覆盖另一个。相反,我这样做:
$response = collect();
foreach ($articleActions as $articleAction) {
$response->push($articleAction);
}
foreach ($referencesWithValidDois as $referencesWithValidDoi) {
$response->doi->push($referencesWithValidDoi);
}
然而它在这里打破了。而当我做这样的事情时:
$response = collect();
foreach ($articleActions as $articleAction) {
$response->push($articleAction);
}
$response['doi'] = [];
foreach ($referencesWithValidDois as $referencesWithValidDoi) {
$response['doi'] = $referencesWithValidDoi;
}
它有点工作,但它发回一个像这样的对象:
其中属性在迭代中doi
被当前覆盖。$referencesWithValidDoi
因此,目前,它被发回为:
0: {...},
1: {...},
2: {...},
3: {...},
doi: {...}
但是我该如何写它,以便将其发送回:
0: {...},
1: {...},
2: {...},
3: {...},
doi: {
0: {...},
1: {...},
2: {...},
...
}
编辑:这样做,
$response = collect();
foreach ($articleActions as $articleAction) {
$response->push($articleAction);
}
$response['doi'] = [];
foreach ($referencesWithValidDois as $referencesWithValidDoi) {
$response['doi'][] = $referencesWithValidDoi;
}
引发错误:
Indirect modification of overloaded element of Illuminate\Support\Collection has no effect
解决方案
以 laravel 集合的方式对此的正确方法如下,
$response = $articleCollection->put('doi', $referencesWithValidDois);
推荐阅读
- node.js - TypeError('JwtStrategy 需要一个秘密或密钥')
- php - Heredoc 究竟如何处理花括号?
- visual-studio-code - 在远程 ssh 连接时,文件不会从 vscode 集成终端打开
- spring - 如何将 application.properties 参数列表转换为 application.yml
- swift - 错误:线程 1:“无法设置未准备好约束的视图层次结构的布局。” 使用自动布局时
- firebase - 从 listview 子小部件获取数据,该小部件不涉及 Flutter 中预先编写的全局键列表
- powershell - 如何使用函数参数
- sql - 选择查询中的一个或多个必需参数没有给出值
- android - 如何在 BaseActivity 中使用刀柄进行变量注入
- android - 由于 androidx.core:core-ktx 导致的 Ionic cordova 运行错误