当我在生产中运行数据库种子脚本时,会发生内存耗尽。
下面是我的种子脚本。
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/