首页 > 解决方案 > 集合上的 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

标签: phplaraveleloquent

解决方案


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;

推荐阅读