2016-03-12 74 views
8

我安裝和配置Laravel 5.2,其做工精細,爲User ACL我安裝了zizaco/entrust包運行此命令php artisan migrate而(用於創建rolespermissions表等)越來越以下錯誤Laravel 5.2委託遷移錯誤,無法添加外鍵約束

[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table role_user add constraint role_user_user_id_foreign foreign key (user_id) references `` (id) on delete cascade on update cascade)

[PDOException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

可能是什麼原因?我錯過了什麼嗎?我遵循從步驟明智的指導原則委託site

回答

17

我修正了這個問題,在委託遷移文件中,有users表名不見了。看到下面的行

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

所以我改變了這一點,

$table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');

我加入了users表的名稱,問題是固定的。

原因,爲什麼我得到這個問題?

config/auth.php文件,有沒有在提供商陣列提及'table'=>'users'鍵/對,見下文(這是默認情況下,裝置被安裝新鮮laravel時)

'providers' => [ 
    'users' => [ 
     'driver' => 'eloquent', 
     'model' => App\User::class, 
    ], 

php artisan entrust:migration命令運行時,它拉users表名從上面的providers數組中,如果在遷移文件中沒有提到那麼表,則關係設置爲這樣的空。

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

因此,像這樣在提供者數組中添加表。

'providers' => [ 
    'users' => [ 
     'driver' => 'eloquent', 
     'model' => App\User::class, 
     'table'=>'users' 
    ], 

的委託遷移php artisan entrust:migration是運行命令後,這將產生正確的遷移文件。

1

當我試圖在相同的遷移中添加外鍵(相同的Schema::create塊)時,我有時會得到相同的錯誤。如果我創建遷移在那裏我創造新柱:

Schema::create(... 
    ... 
    $table->integer('categories_id')->unsigned(); 
    ... 
}); 

然後在同一個文件中我設置此列作爲外鍵:

Schema::table('sub_categories', function (Blueprint $table) { 
    $table->foreign('categories_id')->references('id')->on('main_categories'); 
}); 

它完美。

希望這會幫助你。