Laravel 收集后无法展平数组->忘记

Laravel cant flatten array after collection->forget

我在 Laravel 集合上有一个内循环,有时我需要从第二个循环集合中删除一些 object。这是代码

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 的集合从简单(非关联)数组变为 object。这是响应的示例

我正在尝试展平 $group->templates->flatten() 但最终响应模板仍然是 object 但不是数组。

这个测试展平有效

    ...
    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
    }

但最终变体还是returns我object而不是数组

    $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)
}

使用values()重置键值和setRelation()替换关系:

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->setRelation('templates', $group->templates->forget($key)->values());
            }
        }
    }

    return $all_groups;
}

您也可以使用 except() 代替 forget():

public function remove_if_found($id)
{
    $all_groups = Group::all();
    $all_groups->load('templates');

    foreach ($all_groups as $group)
    {
        $group->setRelation('templates', $group->templates->except($id));
    }

    return $all_groups;
}