php - 集合上的 Laravel 块将第一个元素作为数组返回,第二个作为对象返回
问题描述
我从模型中获取所有记录,但我需要从中获取块,我只需要的值email
所以我映射它
$forwadings = \App\Models\ForwardingEmail::where('company_id', $companyId)
->where('status', 1)
->get(['email']);
->map(function($forwarding) {
return $forwarding['email'];
})
return $forwadings;
返回显示这个
[
"email12@example.com",
"email13@example.com",
"email1@example.com",
"email2@example.com",
"email3@example.com",
"email6@example.com",
"email7@example.com",
"email8@example.com",
"email4@example.com",
"email5@example.com",
"email9@example.com",
"email10@example.com"
]
这里的问题是当我这样做时return $forwardings->chunk(10)
,它显示了这一点:
[
[
"email12@example.com",
"email13@example.com",
"email1@example.com",
"email2@example.com",
"email3@example.com",
"email6@example.com",
"email7@example.com",
"email8@example.com",
"email4@example.com",
"email5@example.com"
],
{
"10": "email9@example.com",
"11": "email10@example.com"
}
]
为什么会这样?我该如何解决这个问题?我尝试toArray
在块结果上使用但没有用。我正在使用 laravel 5.3
解决方案
Laravel 的方法对所有分块项->chunk()
应用递增。id
在转换为 JSON 时,这是一个问题,因为 JavaScript 不允许数组以偏移键值开头(不是以 0 开头),因此必须将它们定义为对象。
您可以进行自己的处理以删除键值。像这样的东西应该工作。
$chunks = \App\Models\ForwardingEmail::where('company_id', $companyId)
->where('status', 1)
->pluck('email')
->chunk(10);
foreach ($chunks as $key => $chunk) {
$chunks[$key] = array_values($chunk->toArray());
}
return $chunks;
推荐阅读
- php - 通过单击“选项”插入我的目录图像
- sql - SQL在插入时如何截断数据?
- javascript - 由于错误的延迟 Javascript,图像滑块无法正常工作
- git - 删除来自 master 分支的不需要的提交
- sql - 修复嵌套聚合函数
- jasmine - 模拟在目标类中实例化的类
- react-native - React Native:更新变量内的文本
- javascript - 将“Thu Sep 19 14:24:59 UTC 2019”转换为时刻日期
- php - 当我尝试将数据保存在数据库中时,我在 laravel SplFileInfo::getSize() 中收到此错误
- android - Flutter Android ERROR:ensureInitializationComplete 必须在 startInitialization 之后调用