Use Laravel seed and sql files to populate database

后端 未结 4 1659
忘了有多久
忘了有多久 2021-01-30 11:28

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?

4条回答
  •  遇见更好的自我
    2021-01-30 12:01

    @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

提交回复
热议问题