2016-02-13 68 views
1

我正嘗試使用Laravel的遷移來創建外鍵。Laravel外鍵有什麼問題?

Schema::create('articles', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->integer('user_id')->unsinged(); 
     $table->string('title'); 
     $table->longText('body'); 
     $table->timestamp('published_at'); 
     $table->timestamps(); 

    }); 


    Schema::table('articles', function($table) { 
     $table->foreign('user_id') 
      ->references('id') 
      ->on('users') 
      ->onDelete('cascade'); 

    }); 

我收到以下錯誤,當我做php artisan migrate

[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter ta ble laravel_articles add constraint articles_user_id_foreign foreign key (user_id ) references laravel_users (id) on delete cascade) `

+0

'unsinged();'?!? –

+0

@MarkBaker不起作用! – Ahmad

+0

這是相同的遷移嗎? – Dencker

回答

4

你有方法的名稱拼寫錯誤。它應該是unsigned()unsinged()

Schema::create('articles', function (Blueprint $table) { 
    $table->increments('id'); 
    $table->integer('user_id')->unsigned(); 
    $table->string('title'); 
    $table->longText('body'); 
    $table->timestamp('published_at'); 
    $table->timestamps(); 
}); 

的架構Builder使用Fluent到鏈中的方法,即使鏈式方法unsinged不存在不拋出異常。儘管有錯字,articles表仍然會被創建,但user_id列將是一個有符號的整數,並且由於users表中的id列是無符號整數,所以它將阻止創建約束。

+0

令人驚歎的感謝的人。 :-) – Ahmad