【发布时间】:2019-10-04 23:13:17
【问题描述】:
我在 Laravel 集合中有一个循环内循环,有时我需要从第二个循环集合中删除一些对象。这是代码
public function remove_if_found($id)
{
$all_groups = Group::all();
$all_groups->load('templates');
foreach ($all_groups as $group)
{
foreach ($group->templates as $key => $template)
{
if($template->id = $id)
{
$group->templates->forget($key);
}
}
}
return $all_groups;
}
问题是 group->templates 的集合从简单(不是 assoc)数组变成了对象。这是响应的外观示例
我正在尝试展平 $group->templates->flatten() 但在最终响应中,模板仍然是对象,而不是数组。
这个测试展平有效
...
foreach ($all_groups as $group)
{
foreach ($group->templates as $key => $template)
{
if($template->id = $id)
{
$group->templates->forget($key);
}
}
return $group->templates->flatten()//This code works i get fluttened array
}
但最终变体仍然返回我对象而不是数组
$all_groups = Group::all();
$all_groups->load('templates');
foreach ($all_groups as $group)
{
foreach ($group->templates as $key => $template)
{
if($template->id = $id)
{
$group->templates->forget($key);
}
}
$group->templates->flatten()//Use flatten here
}
return $all_groups;//Templates are returned not as an array but still as an object (Same variant as on attached image)
}
【问题讨论】:
标签: laravel orm eloquent relational-database