Laravel - 播种大型 SQL 文件

2024-03-21

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

下面是我的种子脚本。

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);
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Laravel - 播种大型 SQL 文件 的相关文章

随机推荐