2016-01-20 52 views
0

我有這四個表,但我在Laravel雄辯中得到了上述錯誤。任何人都可以告訴我在這裏錯過了什麼?但是,當我刪除外部方法遷移工作正常。獲取錯誤:SQLSTATE [HY000]:一般錯誤:1215無法在Laravel 5中添加外鍵約束

Schema::create('students', function (Blueprint $table) { 
     $table->increments('id')->unsigned(); 
     $table->string('first_name'); 
     $table->string('last_name'); 
     $table->string('middle_name'); 
     $table->date('birthdate'); 
     $table->integer('degree_id')->unsigned(); 
     $table->index(['id','first_name', 'last_name']); 
     $table->timestamps(); 

     $table->foreign('degree_id') 
       ->references('id') 
       ->on('degrees'); 


    }); 

我包括無符號方法,但仍然得到上述錯誤。

Schema::create('degrees', function (Blueprint $table) { 
     $table->increments('id')->unsigned(); 
     $table->string('description'); 
     $table->string('category_id'); 
     $table->integer('duration'); 
     $table->string('sub_code'); 
     $table->timestamps(); 

     $table->foreign('sub_code') 
       ->references('id') 
       ->on('courses'); 
    }); 

下面是另外兩張表。

 Schema::create('instructors', function (Blueprint $table) { 
     $table->increments('id')->unsigned(); 
     $table->string('first_name'); 
     $table->string('middle_name'); 
     $table->string('last_name'); 
     $table->date('birthdate'); 
     $table->index(['id', 'first_name', 'last_name']); 
     $table->timestamps(); 
    }); 

而最後的表:

Schema::create('courses', function (Blueprint $table) { 
     $table->string('id')->unique(); 
     $table->string('description'); 
     $table->integer('no_of_units'); 
     $table->string('room_id'); 
     $table->date('schedule');   
     $table->integer('instructor_id')->unsigned(); 
     $table->timestamps(); 

     $table->foreign('instructor_id') 
       ->references('id') 
       ->on('instructors'); 

    }); 
+0

也看看這裏:http://stackoverflow.com/questions/22615926/migration-cannot-add-foreign-key-constraint-in-laravel –

回答

1

的遷移文件的順序很重要。如果您在degrees表之前首先創建students表,則外鍵約束將失敗,因爲degrees表尚未創建。

要解決此問題,您可以將所有外鍵約束移動到應該最後運行的遷移create_foreign_key_constraints_migration

+0

謝謝我會嘗試 –

+0

@CodeProject有freate_foreign_key錯誤表仍然是相同的。 –

相關問題