Laravel 数据库插入错误:允许的内存大小已用尽

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12443321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 15:48:35  来源:igfitidea点击:

Laravel DB Insert Error: Allowed Memory Size Exhausted

phplaravelmemory-limit

提问by csm232s

I'm running into an issue when trying to insert ~20K records into my DB. I notice that even though I'm echoing inside my foreach loop, I'm not getting anything outputted in the command line. Instead, I get an error after inserting ~9440 records relating to...

我在尝试将 ~20K 记录插入到我的数据库时遇到了一个问题。我注意到,即使我在 foreach 循环中回显,我也没有在命令行中输出任何内容。相反,在插入与...相关的约 9440 条记录后,我收到错误消息。

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 91 bytes) in /Users/me/Sites/Laravel/database/connection.php on line 293

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 91 bytes) in /Users/me/Sites/Laravel/database/connection.php on line 293

Here is my code (tried using both Eloquent and Fluent):

这是我的代码(尝试使用 Eloquent 和 Fluent):

<?php

class Process_Controller extends Base_Controller
{
    public function action_migrate()
    {
        $properties = DB::table('raw_properties')->get('id');
        $total = count($properties);

        foreach ($properties as $x => $p) {
            $r = RawProperty::find($p->id);
            $count = $x + 1;

            $prop_details = array(
                'column' => $r->field,
                // Total of 21 fields
            );

            DB::table('properties')->insert($prop_details);

            echo "Created #$count of $total\n";
        }
    }
}

采纳答案by Rubin Porwal

This error depicts that your PHP script has exhausted memory limit due to insufficient memory allocated for script.

此错误表示由于为脚本分配的内存不足,您的 PHP 脚本已用尽内存限制。

You need to increase memory_limit using the ini_set function e.g ini_set('memory_limit','128M');

您需要使用 ini_set 函数来增加 memory_limit,例如 ini_set('memory_limit','128M');

回答by Erik

The accepted answer is fixing the symptom rather then the problem. The problem is the Laravel query log (in memory) is eating all your RAM when you execute such a large # of queries. See the answer here: https://stackoverflow.com/a/18776710/221745

公认的答案是解决症状而不是问题。问题是当您执行如此大量的查询时,Laravel 查询日志(在内存中)会占用您所有的 RAM。在此处查看答案:https: //stackoverflow.com/a/18776710/221745

Or, in brief, turn off query logging via:

或者,简而言之,通过以下方式关闭查询日志记录:

DB::disableQueryLog()

Before executing 20k queries

在执行 20k 查询之前