在 Laravel 迁移文件中,我有以下代码:
Schema::table('stripe_customers', function (Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
“user_id”是“stripe_customers”表中现有的无符号整数列。
“id”是“users”中的主键列。
但是,当我运行迁移命令时,我收到以下错误消息:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table 'thedealerapp.#sql-47a_78859' (errno: 150) (SQL:
alter table `stripe_customers` add constraint stripe_customers_user_id_foreign foreign key (`user_id`)
references `users` (`id`))
[PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table 'thedealerapp.#sql-47a_78859' (errno: 150)
为什么会这样?
最佳答案
因此,创建外键失败的可能原因有多种。
users
.id
是否已编入索引? MySQL 需要在两个表上都有索引才能创建外键。虽然stripe_customers
.user_id
是隐式创建的,但请确保users
.id
.stripe_customers
中是否有可能无法通过外键检查的内容?这会导致创建外键时出错。- 您是否确认两个表的列类型相同? MySQL 将要求两者相同
- 您能否确认这两个表处于同一架构中?如果您的一个表以某种方式位于不同的数据库中,那么 MySQL 需要对该数据库的显式引用。
关于mysql - 无法在 Laravel 中添加外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42420467/