2015-11-10 102 views
8

我想寫一個laravel數據庫遷移,但我發現有關外鍵的以下錯誤:Laravel遷移無法添加外鍵

[Illuminate\Database\QueryException]                                                      
    SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'category_id' doesn't exist in table (SQL: alter table `subcategories` add constraint subcategories_category_id_foreign foreign key (`category_id`) references `categories` (`id`)) 



    [PDOException]                       
    SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'category_id' doesn't exist in table 

確實會產生的categoriessubcategories表,但外鍵不。這是我的遷移:

<?php 

use Illuminate\Database\Schema\Blueprint; 
use Illuminate\Database\Migrations\Migration; 

class CreateCategoryTable extends Migration 
{ 
    /** 
    * Run the migrations. 
    * 
    * @return void 
    */ 
    public function up() 
    { 
     Schema::create('categories', function ($table) { 
      $table->increments('id')->unsigned(); 
      $table->string('name')->unique(); 
     }); 

     Schema::create('subcategories', function ($table) { 
      $table->increments('id')->unsigned(); 
      $table->foreign('category_id')->references('id')->on('categories'); 
      $table->string('name')->unique(); 
     }); 
    } 

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

任何想法?謝謝!

+0

您不需要將自動遞增字段作爲無符號外鍵引用。 –

回答

18

你應該建立一個外鍵之前創建列:

$table->integer('category_id')->unsigned(); 
$table->foreign('category_id')->references('id')->on('categories'); 

文檔:http://laravel.com/docs/5.1/migrations#foreign-key-constraints

+0

哦!愚蠢的錯誤。謝謝! –

+0

@RoemerBakker如果你對我的回答感到滿意,你可以接受它:) –

+0

很高興能這麼做!昨天當您回答時,必須再等5分鐘,之後忘記接受。祝你今天愉快! ; ) –

0

我忘了補充->get()給我打電話的方法。