mysql - SQLSTATE[HY000]: 一般错误: 1005 Can't create table `test`.`members` (errno: 150 "Foreign key constraint is wrongly forms")
问题描述
我在 Laravel 中使用我的迁移来创建表之间的关系,我有 4 个表:用户、成员、成员技能和技能。我有用户表的以下代码:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->boolean('admin');
});
}
成员表:
public function up()
{
Schema::create('members', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('name');
$table->string('status');
$table->date('date')->nullable();
$table->text('project')->nullable();
$table->date('start')->nullable();
$table->foreign('name')->references('name')->on('users');
});
}
member_skills 表:
public function up()
{
Schema::create('member_skills', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('name');
$table->string('skill');
$table->foreign('name')->references('name')->on('members');
});
}
和技能表:
public function up()
{
Schema::create('skills', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('skill');
$table->text('description');
$table->foreign('skill')->references('skill')->on('member_skills');
});
}
但是,运行我的迁移会导致(errno: 150 "Foreign key constraint is incorrectly formed")
. 我已经读过更改迁移顺序应该可以解决问题,所以我按照用户、成员、成员技能和技能的顺序排列了要迁移的 4 个表,但我仍然收到同样的错误。还有什么我做错了吗?
解决方案
这是执行此操作的正确方法
public function up()
{
Schema::create('members', function (Blueprint $table) {
...
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
}
public function up()
{
Schema::create('member_skills', function (Blueprint $table) {
...
$table->unsignedBigInteger('member_id');
$table->foreign('member_id')->references('id')->on('members');
});
}
public function up()
{
Schema::create('skills', function (Blueprint $table) {
...
$table->unsignedBigInteger('member_skill_id');
$table->foreign('member_skill_id')->references('id')->on('member_skills');
});
}
更多:https ://laravel.com/docs/8.x/migrations#foreign-key-constraints
推荐阅读
- python - 不允许主机连接到此 MySQL 服务器(来自 VM)
- asp.net-core - 在 asp.net 核心控制器中,HTTP 上下文为空
- c# - 如何在 VirtoCommerce 中发送通知
- javascript - Javascript | 'element.style.display' 状态检查在'if gate' 中不起作用?
- c++ - 在 boost::spirit::x3 中合成 std::pair 属性
- excel - VBA 将行数复制到新工作簿
- mysql - 与 CONCAT 一起使用时,SQL 命令在查询中挂起
- visual-studio - Visual Studio 2019 - 代码图:禁用源类/dotnet 核心的“直接”引用
- php - PHP数组:如何使用不同的值进行查询
- sql - 从 SQL 到 Laravel 查询构建器