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

33,960

Solution 1

As the error says, you can not truncate tables referenced by foreign keys. Delete should work though...

DB::table('some_table')->delete();

Solution 2

DB::statement('SET FOREIGN_KEY_CHECKS=0;');
App\User::truncate();
DB::statement('SET FOREIGN_KEY_CHECKS=1;');

And it works!

Solution 3

before drop

Schema::disableForeignKeyConstraints();

and before close run method

Schema::enableForeignKeyConstraints();

Solution 4

To clear a table using Eloquent:

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

Example using default user model

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

Solution 5

I faced the same issue with my Role and Permission setup and this is what I did that worked as I wanted. Truncate() will reset the Increment column to 1 but throw a foreign key error while delete on the other hand works fine but doesn't reset the increment column, so I did the following in my Seeder's file (i.e RoleSeeder.php in my case)

1. [ delete() method ]

$roles = [];

... // Some foreach statement to prepare an array of data for DB insert()

// Delete and Reset Table
DB::table('roles')->delete();
DB::statement("ALTER TABLE `roles` AUTO_INCREMENT = 1");
// Insert into table
DB::table('roles')->insert($roles);

This will cascade all other child tables attached to the roles table. in my case users_roles table. This way I avoided disabling and enabling foreign key checks.

2. Something to put in mind / Second Approach [ truncate() method ]

if you don't have the intention of deleting all the data stored in the child's table (in my case users_roles table) ... You can go with truncate() and then in the DatabaseSeeders.php file you disable and enable foreign key check. As I tested this and the users_roles data was intact, the seed on affected roles table.

//RoleSeeders.php File

$roles = [];

... // Some foreach statement to prepare an array of data for DB insert()

// Truncate Table
DB::table('roles')->truncate();
// Insert into table
DB::table('roles')->insert($roles);

Then in the DatabaseSeeder.php file, you do;

public function run()
{
    DB::statement('SET FOREIGN_KEY_CHECKS=0;');

    $this->call([
        RoleSeeder::class,
    ]);

    DB::statement('SET FOREIGN_KEY_CHECKS=1;');
}

But I prefer the delete() method, since I don't have to disable/enable the foreign key check

Share:
33,960
mtpultz
Author by

mtpultz

Life is all about managing your time effectively and finding a balance between work and play. In development, I found the balance between the front- and back-end work provides a lot of job satisfaction and diversity of work. Through my work experience as a full-stack developer I have a well-balanced set of skills for web application development, which include a proficiency to learn new languages and frameworks on demand, ability to communicate not only with other developers but with customers, production of well-documented and maintainable code that include automated tests, experience with deployment and clouds services like Digital Ocean and CircleCI, as well as familiarity with Linux, command-line, virtual environments (Vagrant), containers (Docker), and version control (Git).

Updated on January 07, 2021

Comments

  • mtpultz
    mtpultz over 3 years

    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:

    Migration table created successfully.
    Migrated: 2015_06_17_100000_create_users_table
    Migrated: 2015_06_17_200000_create_password_resets_table
    Migrated: 2015_06_17_300000_create_vehicles_table
    
    [Illuminate\Database\QueryException]
    SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table
    referenced in a foreign key constraint (`app`.`vehicles`, CONSTRAINT `vehic
    les_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `app`.`users` (`id`
    )) (SQL: truncate `users`)
    
    [PDOException]
    SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table
    referenced in a foreign key constraint (`app`.`vehicles`, CONSTRAINT `vehic
    les_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `app`.`users` (`id`
    ))
    

    I looked up what this error is supposed to mean, and also found examples of other people running into the same problem, even just related to using MySQL, and their solutions, but applying:

    DB::statement('SET FOREIGN_KEY_CHECKS=0;'); and 
    DB::statement('SET FOREIGN_KEY_CHECKS=1;'); 
    

    Within down() doesn't seem to work and when I run describe in MySQL the tables look right.

    The migrations are named properly to make sure the users table is migrated first, and then vehicles so the foreign key can be applied, and the tables being setup up correctly suggests the migrations were run, but then the error occurs. I dropped and recreated the DB and tried it again and it is the same result. I also don't understand why it is trying to truncate on the first migration and seed of the database, I wouldn't have thought that would occur when you tried to run php artisan migrate:refresh --seed.

    // 2015_06_17_100000_create_users_table.php
    
    class CreateUsersTable extends Migration
    {
        public function up()
        {
            Schema::create('users', function (Blueprint $table) {
                $table->increments('id');
                $table->string('username', 60)->unique();
                $table->string('email', 200)->unique();
                $table->string('password', 255);
                $table->string('role')->default('user');
                $table->rememberToken();
                $table->timestamps();
            });
        }
    }
    
    public function down()
    {
        Schema::drop('users');
    }
    
    // 2015_06_17_300000_create_vehicles_table.php
    
    class CreateVehiclesTable extends Migration
    {
        public function up()
        {
            Schema::create('vehicles', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('user_id')->unsigned();
                $table->string('make');
                $table->string('model');
                $table->string('year');
                $table->string('color');
                $table->string('plate');
                $table->timestamps();
    
                $table->foreign('user_id')->references('id')->on('users');
            });
        }
    }
    
    public function down()
    {
        Schema::drop('vehicles');
    }