【问题标题】:Laravel cant flatten array after collection->forget收集后Laravel无法展平数组->忘记
【发布时间】: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


    【解决方案1】:

    使用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;
    }
    

    【讨论】:

    • 是的,它可以工作,现在一切正常,我不明白 setRelation 是做什么的,现在将 google 一下,谢谢)
    • 它在Model::$relations 属性中设置关系的值。
    • 这有点像“临时”关系?
    • 不,它会替换现有值。对于属性,您可以使用 $group->name = strtolower($group->name); 之类的东西。对于关系,这需要setRelation()
    • 你太棒了,谢谢乔纳斯)
    猜你喜欢
    • 2020-05-07
    • 2019-11-03
    • 2020-04-27
    • 2018-05-31
    • 2019-05-15
    • 2019-10-12
    • 2018-03-27
    • 1970-01-01
    • 2011-09-06
    相关资源
    最近更新 更多