Laravel无法添加外键约束 [英] Laravel cannot add foreign key constraint
问题描述
当我尝试在laravel 5中通过迁移设置外键约束时,收到错误消息:
When I'm trying to set a foreign key constraint in laravel 5 with migrations I receive the error:
[Illuminate \ Database \ QueryException] SQLSTATE [HY000]:常规 错误:1215 无法添加外键约束(SQL:Alter表
rittenregistratie
添加约束 rittenregistratie_karakterrit_id_foreign外键 (karakterrit_id
)在删除时引用karakterrit
(id
) 级联)[PDOException] SQLSTATE [HY000]:一般错误:1215 无法添加外键约束D:\ wamp \ www>
[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table
rittenregistratie
add co nstraint rittenregistratie_karakterrit_id_foreign foreign key (karakterrit_id
) referenceskarakterrit
(id
) on delete cascade) [PDOException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint D:\wamp\www>
但是我现在知道为什么了吗???迁移顺序正确,为什么我会收到此错误?表rittenregistratie具有一个名为karakterrit_id的外键,这是表karakterrit中的主键.
But I have now idea why??? The order of migrating is right so why do I receive this error? The table rittenregistratie has a foreign key called karakterrit_id this is the primary key in the table karakterrit.
这是我的迁移rittenregistratie:
This is my migration rittenregistratie:
public function up()
{
Schema::create('rittenregistratie', function (Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->timestamps('datum');
$table->integer('beginstand');
$table->integer('eindstand');
$table->text('van');
$table->text('naar');
$table->text('bezoekadres');
$table->text('geredenroute');
$table->integer('karakterrit_id')->default(1);
$table->text('toelichting');
$table->integer('kilometerszakelijk');
$table->integer('kilomteresprive');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('karakterrit_id')
->references('id')
->on('karakterrit')
->onDelete('cascade');
});
}
推荐答案
添加
$table->integer('karakterrit_id')->unsigned()->default(1);
您已创建查询中使用的users
表和karakterrit
.如果同时具有两个表,请检查迁移文件的创建日期,然后再创建引用它们的其他表.
Have you created the users
Table and karakterrit
that you used in your query. If you have both tables, check the creation date of the migration files they both should be created before other table that references them.
另一个问题可能是不支持的MyISAM
.而是使用InnoDB
Another problem might be MyISAM
which does not support. Instead use InnoDB
DB::statement('ALTER TABLE categories ENGINE = InnoDB');
这篇关于Laravel无法添加外键约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!