本文介绍了Laravel迁移不会添加外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是迁移的新手,尝试创建2个带有外键的表,其中一个在另一个表中引用一个ID,但是我普遍无法添加键错误.有什么我想念的吗?
I am new to migrations and attempting to create 2 tables with a foreign key in one referencing an id in the other but I am getting a general failure to add key error. is there something I am missing?
错误:
[PDOException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
[PDOException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
代码:
Schema::create('app_groups', function($table) {
$table->increments('id');
$table->string('app_name');
$table->unsignedInteger('app_group_id');
$table->timestamps();
});
Schema::create('app_to_bucket', function($table) {
$table->increments('id');
$table->unsignedInteger('app_group_id');
$table->unsignedInteger('bucket_id');
$table->timestamps();
});
Schema::table('app_to_bucket', function($table) {
$table->foreign('app_group_id')->references('app_group_id')->on('app_groups')->onDelete('cascade');
});
推荐答案
我已经解决了问题.
问题是Laravel自动假定递增列为主键.所以我需要指定我的app_group_id
是主键.
The issue was that Laravel automatically assumes incrementing columns as the primary key. so I needed to specify that my app_group_id
was the primary key.
Schema::create('app_groups', function($table) {
$table->string('app_name');
$table->integer('app_group_id');
$table->primary('app_group_id');
$table->timestamps();
});
Schema::create('app_to_bucket', function($table) {
$table->integer('app_group_id');
$table->integer('bucket_id');
$table->primary('bucket_id');
$table->timestamps();
});
Schema::table('app_to_bucket', function($table) {
$table->foreign('app_group_id')->references('app_group_id')->on('app_groups')->onDelete('cascade');
});
这篇关于Laravel迁移不会添加外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!