본문 바로가기
MySql

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

by 베이스 공부 2020. 11. 19.
반응형

마이그레이션 (아래 참조)을 실행하고 데이터베이스를 시드하려고하지만 실행하면

php artisan migrate --seed

이 오류가 발생합니다.

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`
))


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

down () 내에서 작동하지 않는 것 같고 MySQL에서 describe를 실행하면 테이블이 올바르게 보입니다.

마이그레이션의 이름은 사용자 테이블이 먼저 마이그레이션되었는지 확인한 다음 외래 키를 적용 할 수 있도록 차량을 지정하고, 설정중인 테이블은 마이그레이션이 실행되었음을 올바르게 제안하지만 오류가 발생합니다. DB를 삭제하고 다시 생성하고 다시 시도했는데 같은 결과입니다. 나는 또한 그것이 데이터베이스의 첫 번째 마이그레이션과 시드에서 자르기를 시도하는 이유를 이해하지 못합니다.

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

 

해결 방법

 

오류에서 알 수 있듯이 외래 키가 참조하는 테이블을자를 수 없습니다. 그래도 삭제가 작동합니다 ...

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

 

참조 페이지 https://stackoverflow.com/questions/31192207

 

 

반응형

댓글