【问题标题】:Laravel Eloquent - Save/Update Related One-To-Many Relationship DataLaravel Eloquent - 保存/更新相关的一对多关系数据
【发布时间】:2015-04-12 15:49:28
【问题描述】:

我有一个包含许多项目的实体集。因此,在更新集合时,表单也包含更新其项目的字段。我已经做到了,并且运行良好,但我不确定这是否是正确和最有效/最优雅的方式。这是我的代码:

        $set->fill(Input::all());

        foreach (Input::get('course') as $course_id => $content) {
            $item = $set->items->filter(function ($item) use ($course_id) {
                return ($item->course_id == $course_id);
            })->first();
            $item->content = $content;
            $set->items()->save($item);
        }
        $set->save();

如您所见,对于每个项目,我遍历了所有输入(可能会因输入的数量而异),对其进行过滤,并将值 1 乘 1 保存。因此,每次迭代都会执行一个查询。我使用过滤器,这样它就不必为每次检查进行查询。

所以我的问题是,有没有更有效/优雅的方法来做到这一点?可能像 saveMany() 这样的东西?

【问题讨论】:

    标签: php laravel eloquent relationship


    【解决方案1】:

    您可以像这样使用 saveMany 方法:

            $set->fill(Input::all());
            $items = array();
            foreach (Input::get('course') as $course_id => $content) {
                $item = $set->items->filter(function ($item) use ($course_id) {
                    return ($item->course_id == $course_id);
                })->first();
                $item->content = $content;
                $items[] = $item;
            }
    
            $set->items()->saveMany($items);
            $set->save();
    

    正如laravel docs的相关模型中指出的那样

    【讨论】:

    • 是的,我看到了,我想您不需要将特定的 Collection 对象传递给 saveMany()。我们可以像你一样使用简单的数组。测试并验证它的工作。谢谢。
    猜你喜欢
    • 2017-07-17
    • 1970-01-01
    • 2014-09-02
    • 2016-07-22
    • 2013-02-09
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    相关资源
    最近更新 更多