Laravel 5.1 Migration and Seeding Cannot truncate a table referenced in a foreign key constraint

前端 未结 9 2141
借酒劲吻你
借酒劲吻你 2020-12-15 05:04

I\'m trying to run the migration (see below) and seed the database, but when I run

php artisan migrate --seed

I get this error:

<         


        
相关标签:
9条回答
  • 2020-12-15 05:34

    To clear a table using Eloquent:

    Model::query()->delete();
    

    Example using default user model

    User::query()->delete();
    
    0 讨论(0)
  • 2020-12-15 05:35

    before drop

    Schema::disableForeignKeyConstraints();
    

    and before close run method

    Schema::enableForeignKeyConstraints();
    
    0 讨论(0)
  • 2020-12-15 05:35

    I'm using Laravel 7.x, this worked for me. Goes without saying that it should only be used in development. To read more, check it out here.

    DatabaseSeeder.php

        <?php
    
    use Illuminate\Database\Seeder;
    
    class DatabaseSeeder extends Seeder
    {
        /**
         * Seed the application's database.
         *
         * @return void
         */
        public function run()
        {
            // the Eloquent part and disabling and enabling of foreign keys is only intended for development
            Eloquent::unguard();
    
            //disable foreign key check for this connection before running seeders
            DB::statement('SET FOREIGN_KEY_CHECKS=0;');
    
            $this->call(RolesTableSeeder::class);
            $this->call(UsersTableSeeder::class);
    
            // supposed to only apply to a single connection and reset it's self
            // but I like to explicitly undo what I've done for clarity
            DB::statement('SET FOREIGN_KEY_CHECKS=1;');
        }
    }
    
    0 讨论(0)
提交回复
热议问题