我从github上获得了世界上几个国家,州和城市的.sql文件。 如何使用 Laravel 的种子文件运行它们以填充数据库中的这些表?
- 将
DB::unprepared()
添加到DatabaseSeeder
的运行方法中。 -
在命令行运行
php artisan db:seed
。class DatabaseSeeder extends Seeder { public function run() { Eloquent::unguard(); $this->call('UserTableSeeder'); $this->command->info('User table seeded!'); $path = 'app/developer_docs/countries.sql'; DB::unprepared(file_get_contents($path)); $this->command->info('Country table seeded!'); } }
我找到了一个从数据库表和行创建种子文件的包。它目前支持 Laravel 4 到 10:
https://github.com/orangehill/iseed
最后,它基本上就这么简单:
php artisan iseed my_table
或多次:
php artisan iseed my_table,another_table
正如其他答案所使用的那样,DB::unprepared
不适用于更复杂的SQL文件。
另一个更好的解决方案是直接在进程中使用 MySQL cli:
$process = new Process([
'mysql',
'-h',
DB::getConfig('host'),
'-u',
DB::getConfig('username'),
'-p' . DB::getConfig('password'),
DB::getConfig('database'),
'-e',
"source path/to/schema.sql"
]);
$process->mustRun();
> 2022 安德鲁·科佩尔的简化答案:
class WhateverSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$file_path = resource_path('sql/whatever.sql');
DB::unprepared(
file_get_contents($file_path)
);
}
}
有趣的事实:60,000 行花了我 50 秒的时间从 JSON 文件导入,这只需要 400 毫秒。
佩尔解决方案是可以理解的,但遗憾的是它对我不起作用。这个有点令人困惑,但至少对我有用。
因此,我不使用DB::unready,而是使用以下内容:
// DatabaseSeeder.php
class DatabaseSeeder extends Seeder {
public function run()
{
// Set the path of your .sql file
$sql = storage_path('a_id_territory.sql');
// You must change this one, its depend on your mysql bin.
$db_bin = "C:wamp64binmariadbmariadb10.3.14bin";
// PDO Credentials
$db = [
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
'host' => env('DB_HOST'),
'database' => env('DB_DATABASE')
];
exec("{$db_bin}mysql --user={$db['username']} --password={$db['password']} --host={$db['host']} --database {$db['database']} < $sql");
}
}
然后在迁移数据库时只需添加 --seed
php artisan migrate:refresh --seed
或
php artisan migrate:fresh --seed
在Laravel7.0.x上测试