Use Laravel seed and sql files to populate database

柔情痞子 提交于 2020-06-24 01:40:57

问题


I got several .sql files of countries, states and cities of the world from github. How can I run them with Laravel's seed files to populate those tables in my database?


回答1:


  1. Add DB::unprepared() to the run method of DatabaseSeeder.
  2. Run php artisan db:seed at the command line.

    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!');
        }
    }
    



回答2:


I found a package that creates seed files from database tables and rows. It currently supports Laravel 4, 5, 6 and 7:

https://github.com/orangehill/iseed

In the end, it's basically as easy as this:

php artisan iseed my_table

or for multiple occasions:

php artisan iseed my_table,another_table



回答3:


@Andre Koper solutions is understandable, but sadly it doesn't work for me. This one is a bit confusing but atleast works for me.

So instead of using DB::unprepared, I use this:

// 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:\wamp64\bin\mariadb\mariadb10.3.14\bin";

       // 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");
    }
}

Then while migrating database just add --seed

php artisan migrate:refresh --seed

or

php artisan migrate:fresh --seed

Tested on Laravel 7.0.x



来源:https://stackoverflow.com/questions/37369452/use-laravel-seed-and-sql-files-to-populate-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!