[英]Cannot add foreign key constraint - Laravel Entrust
我真的不知道出什么問題了,但是我無法在此查詢中添加外鍵約束。
alter table `__acc_role_user` add constraint `__acc_role_user_user_id_foreign` foreign key (`user_id`) references `__acc_accounts` (`account_id`) on delete cascade on update cascade
我如何創建帳戶表?
Schema::create('__acc_accounts', function($table)
{
$table->integer('account_id')->increments();
$table->integer('points')->default(0);
$table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade');
});
然后委托遷移(下面僅是有問題的部分):
Schema::create('__acc_role_user', function (Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->foreign('user_id')->references('account_id')->on('__acc_accounts')
->onUpdate('cascade')->onDelete('cascade');
$table->foreign('role_id')->references('id')->on('__acc_roles')
->onUpdate('cascade')->onDelete('cascade');
$table->primary(['user_id', 'role_id']);
});
這種sintax更好:
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('__acc_accounts', function($table)
{
$table->integer('account_id')->increments();
$table->integer('points')->default(0);
});
Schema::table('__acc_accounts', function(Blueprint $table)
{
$table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('__acc_accounts');
}
而且非常重要! 在您的遷移順序中,必須是:首先創建表“ accounts”,然后創建“ __acc_accounts”。
具有外鍵的表應在創建它們所引用的表之后創建。
此http://blog.kongnir.com/2015/03/08/laravel-order-of-migrations-with-foreign-keys/可以幫助您了解這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.