sql - Laravel - 播种大型 SQL 文件

标签 sql laravel laravel-4 eloquent

当我在生产中运行数据库种子脚本时,会发生内存耗尽。

下面是我的种子脚本。

class MembershipTableSeeder extends Seeder 
{
    public function run()
    {
        DB::table('members')->delete();

        foreach (range(1, 99) as $days){
            Members::create(array('membership_code' => 'test'.$days));
        }

        DB::unprepared(file_get_contents(app_path()."/database/seeds/members.sql"));
    }
}

所以我所做的就是在我的种子脚本上添加无限制。

ini_set('memory_limit', '-1');

现在的问题是,当我运行脚本时,它会将 SQL 脚本的内容(非常非常大)的输出记录到终端中。

是否有一种在数据库种子内运行 SQL 转储且不消耗太多内存的好方法?我现在所做的是手动运行它:

mysql -uuser -p db < script.sql

最佳答案

对于其他更喜欢 Laravel 式解决方案的人,这就是我的处理方式:

/**
 * This class is responsible for running the data dump sql.
 * It is recommended to update this class instead of creating new ones for new database content dumps.
 */
class DatabaseDumpSeeder extends Seeder
{
    /**
     * Run the database seeds.
     * @throws \Exception
     */
    public function run()
    {
        // Note: these dump files must be generated with DELETE (or TRUNCATE) + INSERT statements
        $sql = file_get_contents(__DIR__ . '/dumps/dump-20150709.sql');

        if (! str_contains($sql, ['DELETE', 'TRUNCATE'])) {
            throw new Exception('Invalid sql file. This will not empty the tables first.');
        }

        // split the statements, so DB::statement can execute them.
        $statements = array_filter(array_map('trim', explode(';', $sql)));

        foreach ($statements as $stmt) {
            DB::statement($stmt);
        }
    }
}

关于sql - Laravel - 播种大型 SQL 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25906199/

相关文章:

php - Laravel Collection 循环更新元素

php - 以数组形式返回验证错误并更改为 json

asp.net - 本地主机找不到存储过程 'dbo.aspnet_CheckSchemaVersion'

mysql - 寻找从不存在的数据中删除片段的方法

php - mysql 如何在某些托管站点上编辑 my.ini

php - 如何在php中动态打印多行特定宽度的长字符串

php - 使用 PHP 框架 Laravel 4 在数据库中创建表

mysql - 将表一分为二并保存关系

laravel - 如何通过分页获取 Laravel Eloquent 中的特定列?

php - Laravel 5.0 中不存在方法 [validateA]