为什么我不能使用外键正确创建 table?
Why can't I properly create a table with a foreign key?
我想创建2个table:
- 一个 table 叫
roles
- 还有一个叫做
users
的 table
在 users
中,我想要一个名为 role_id
的列,它应该是对 roles
table.
的引用
roles
table 应该是这样的:
所以这是 user
table 的迁移:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->bigInteger('role_id')->unsigned();
$table->foreign('role_id')->references('role_id')->on('roles');
$table->timestamps();
});
这是 roles
数据库的迁移:
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->string('name');
});
我在 运行 php artisan migrate
时得到的错误
SQLSTATE[HY000]: General error: 1005 Can't create table my_db
.users
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table users
add constraint users_role_id_foreign
foreign key (role_id
) references roles
(role_id
))
有一个定义问题让它像$table->foreign('role_id')->references('id')->on('roles');
或者您需要将角色 table 的主键设置为 role_id
我想这将解决您正在寻找的问题
在引用('id')中更改引用('role_id'),这意味着在角色 table:
中列 'id' 中的引用
$table->foreign('role_id')->references('id')->on('roles');
您还应该先创建角色 table,然后再创建用户 table。
只需像这样更改 database/migrations 上的日期(示例):
2020_09_11_150331_create_roles_table.php
2020_09_12_000000_create_users_table.php
运行:
php artisan migrate
这种方式首先将创建角色 table,然后是用户 table,后者将处理引用角色 table 中的 'id' 列的外键。
我想创建2个table:
- 一个 table 叫
roles
- 还有一个叫做
users
的 table
在 users
中,我想要一个名为 role_id
的列,它应该是对 roles
table.
roles
table 应该是这样的:
所以这是 user
table 的迁移:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->bigInteger('role_id')->unsigned();
$table->foreign('role_id')->references('role_id')->on('roles');
$table->timestamps();
});
这是 roles
数据库的迁移:
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->string('name');
});
我在 运行 php artisan migrate
SQLSTATE[HY000]: General error: 1005 Can't create table
my_db
.users
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter tableusers
add constraintusers_role_id_foreign
foreign key (role_id
) referencesroles
(role_id
))
有一个定义问题让它像$table->foreign('role_id')->references('id')->on('roles');
或者您需要将角色 table 的主键设置为 role_id
我想这将解决您正在寻找的问题
在引用('id')中更改引用('role_id'),这意味着在角色 table:
中列 'id' 中的引用$table->foreign('role_id')->references('id')->on('roles');
您还应该先创建角色 table,然后再创建用户 table。 只需像这样更改 database/migrations 上的日期(示例):
2020_09_11_150331_create_roles_table.php 2020_09_12_000000_create_users_table.php
运行:
php artisan migrate
这种方式首先将创建角色 table,然后是用户 table,后者将处理引用角色 table 中的 'id' 列的外键。