当我在生产中运行我的数据库种子脚本时,会发生内存耗尽。
以下是我的种子脚本。
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
答案 0 :(得分:11)
对于喜欢更多Laravel-ish解决方案的其他人来说,这就是我处理它的方式:
/**
* 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);
}
}
}
答案 1 :(得分:9)
问题出现了,因为当使用Db :: unexpared时它还会将查询记录到laravel.log文件中,在后台进行更多操作然后你会想到,从这一方面你就会耗尽内存。如果你没有运行安全模式,我会坚持执行这样的控制台命令:
exec("mysql -u ".\Config::get('database.mysql.user')." -p".\Config::get('database.mysql.password')." ".\Config::get('database.mysql.database')." < script.sql")
答案 2 :(得分:1)
创建播种文件&#34; PostalCodeTableSeeder.php&#34;在 Project_directory /数据库/种子
use Illuminate\Database\Seeder; class PostalCodeTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // ============================================================= // file Path -> Project/app/configs/database.php // get the database name, database username, database password // ============================================================= $db = \Config::get('database.connections.mysql.database'); $user = \Config::get('database.connections.mysql.username'); $pass = \Config::get('database.connections.mysql.password'); // $this->command->info($db); // $this->command->info($user); // $this->command->info($pass); // running command line import in php code exec("mysql -u " . $user . " -p" . $pass . " " . $db . " < postal_codes.sql"); // postal_codes.sql is inside root folder } }
还要将类名添加到 Project_directory / database / seed / DatabaseSeeder.php,如下面的代码
use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $this->call(PostalCodeTableSeeder::class); // $this->call(UsersTableSeeder::class); } }