使用Laravel种子和sql文件填充数据库

And*_*per 14 laravel-4

我从github获得了世界各国,各州和城市的几个.sql文件.如何使用Laravel的种子文件运行它们来填充数据库中的那些表?

And*_*per 50

  1. 添加DB::unprepared()到run方法中DatabaseSeeder.
  2. 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!');
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)


Ard*_*rda 7

我找到了一个从数据库表和行创建种子文件的程序包。目前,它支持Laravel 4和5:

https://github.com/orangehill/iseed

最后,基本上就像这样简单:

php artisan iseed my_table
Run Code Online (Sandbox Code Playgroud)

或多次:

php artisan iseed my_table,another_table
Run Code Online (Sandbox Code Playgroud)


emo*_*ity 5

2022 年安德鲁·科佩尔 (Andrew Koper) 的简化回答:

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)
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

有趣的事实:从 JSON 文件导入 60,000 行花了我 50 秒,而这只花了 400 毫秒。