yii2循环执行sql的时候

for ($i = 0; $i < $iterations; $i ++) {
    ...
    Yii::$app->db->createCommand()
        ->batchInsert(static::tableName(), $columns, $rows)
        ->execute();
    echo memory_get_usage();
}

会出现500错误,看下php错误日志,大概会看到内存耗尽的提示

[06-Apr-2017 15:55:43 PRC] PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 2077602 bytes) in E:\wamp\www\xxx\vendor\yiisoft\yii2-debug\LogTarget.php on line 57

 

这个是由于yii2的日志模块引起的,具体的大家看看代码,不多说了

解决方案

1、在处理循环sql的时候,替换掉自带的日志模块

2、关掉日志模块

 

具体的看这里

I think that problem is in logger of Yii2. Just try to use something like that:

common/components/EmptyLogger.php:

<?php
namespace common\components;

use yii\log\Logger;

class EmptyLogger extends Logger
{
    public function log($message, $level, $category = 'application')
    {
        return false;
    }
}

and then in your action of your controller include next code at the beginning:

Yii::setLogger(new EmptyLogger());

of course also add it in your uses:

use common\components\EmptyLogger;

after all you will receive something like that:

console\controllers\TempController.php:

<?php

namespace console\controllers;

use common\components\EmptyLogger;
use Yii;
use yii\console\Controller;

class TempController extends Controller
{
    public function actionIndex()
    {
        Yii::setLogger(new EmptyLogger());
        ...

        Yii::$app->db->createCommand()
            ->batchInsert(static::tableName(), $columns, $rows)
            ->execute();
        ...

    }
}

Hope it helps. But actually it's not the best solution. Just a hack..

参考:http://stackoverflow.com/questions/27420959/yii2-batchinsert-eats-all-server-memory

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

et_highlighter