2016-06-20 2 views
0

정말 잘못되었지만이 쿼리에 외래 키 제약 조건을 추가 할 수 없습니다.외래 키 제약 조건을 추가 할 수 없습니다. Laravel Entrust

alter table `__acc_role_user` add constraint `__acc_role_user_user_id_foreign` foreign key (`user_id`) references `__acc_accounts` (`account_id`) on delete cascade on update cascade 

어떻게 계정 테이블을 만들 수 있습니까?

Schema::create('__acc_accounts', function($table) 
    { 
     $table->integer('account_id')->increments(); 
     $table->integer('points')->default(0); 

     $table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade'); 
    }); 

그리고 러스트 마이그레이션 (만 문제가있는 부분은 다음과 같습니다) :

Schema::create('__acc_role_user', function (Blueprint $table) { 
     $table->integer('user_id')->unsigned(); 
     $table->integer('role_id')->unsigned(); 

     $table->foreign('user_id')->references('account_id')->on('__acc_accounts') 
      ->onUpdate('cascade')->onDelete('cascade'); 
     $table->foreign('role_id')->references('id')->on('__acc_roles') 
      ->onUpdate('cascade')->onDelete('cascade'); 

     $table->primary(['user_id', 'role_id']); 
    }); 
+0

외래 키에 인덱스를 추가 했습니까? –

+0

$ table-> integer ('account_id') -> incrementments(); unsigned()이어야합니다 –

+0

예, 인덱스를 외래 키에 추가했습니다. $ table-> integer ('account_id') -> incrementments()를 변경할 때; unsigned() 다음 __acc_accounts 테이블에 대한 동일한 오류가 발생합니다 : SQLSTATE [HY000] : 일반 오류 : 1215 외래 키 제약 조건을 추가 할 수 없습니다. – Tesly

답변

1

이 sintax 낫다 :

/** 
* Run the migrations. 
* 
* @return void 
*/ 
public function up() 
{ 
    Schema::create('__acc_accounts', function($table) 
    { 
     $table->integer('account_id')->increments(); 
     $table->integer('points')->default(0); 
    }); 

    Schema::table('__acc_accounts', function(Blueprint $table) 
{ 
     $table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade'); 
    }); 
} 


/** 
* Reverse the migrations. 
* 
* @return void 
*/ 
public function down() 
{ 
    Schema::drop('__acc_accounts'); 
} 

그리고 매우 중요합니다! 이주 순서는 다음과 같아야합니다. 먼저 'accounts'테이블을 작성한 후 '__acc_accounts'테이블을 작성하십시오.

Tables with foreign keys should be created after the tables they reference to have been created.

http://blog.kongnir.com/2015/03/08/laravel-order-of-migrations-with-foreign-keys/는 TU이를 이해하는 데 도움이 될 수 있습니다.

관련 문제