Laravel - seeding large SQL file

后端 未结 3 1922
后悔当初
后悔当初 2021-02-08 01:41

A memory exhaustion happens when I run my DB seed script in production.

Below is my seed script.

class MembershipTableSeeder extends Seeder 
{
    public         


        
3条回答
  •  广开言路
    2021-02-08 02:39

    For others who prefer a more Laravel-ish solution, this is how I handled it:

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

提交回复
热议问题