2013-07-26 74 views
11

我犯了一個移民與此設置:Laravel 4遷移錯誤 - 創建兩個AUTO_INCREMENT主鍵字段

$table->increments('id'); 
$table->integer('user_id', 10)->unsigned(); // this is meant to be used as a foreign key 

做PHP的工匠後遷移它返回一個錯誤:

[Exception]                                             
SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table definition; 
there can be only one auto column and it must be defined as a key (SQL: create table `transactions` (`id` int unsigned not null auto_increment primary key, `user_id` int unsigned not null auto_increment primary key) default character set utf8 collate utf8_unicode_ci) (Bindings: array()) 

我沒有指定user_id爲auto_increment主鍵,但Migration將其視爲如此。

如何在遷移中創建外鍵?

回答

21

@crynobone:第二個參數是用於確定主鍵的布爾值,沒有整數的長度選項。

參考這裏:https://github.com/laravel/laravel/issues/2212#issuecomment-21608193

+0

那麼你如何處理外鍵? – jrenouard

+2

nvm,在這裏找到答案http://stackoverflow.com/questions/22077573/laravel-migration-will-not-add-foreign-key你應該使用$ table-> integer('app_group_id') - > length(10 ) - >無符號();在Laravel 4 – jrenouard

-2

爲什麼不指定user_id與自動增量的主鍵?

$table->increments('user_id'); 
// other columns 
... 

模式生成器創建user_id,這是10個數字長,無符號&主鍵。

3

在Laravel 4中,整數函數中的第二個參數用於指示整數列是否被自動遞增(也就是說主鍵與否) 在我的情況下,要在表中添加一個自動遞增的ID,我寫它像

$table->integer('id' , true); 

它創建與11位的整數的列。