Laravel 8中的迁移,不允许我将外键放在用户的默认表中
在Laravel的用户表中放置外键时,我有错误。
我有Laravel用户表,我想将其与员工表相关联,该表将具有员工的个人数据,但是当我尝试将外键放入用户表中时,我会遇到一个错误:
pdoexception::(“ sqlstate [hy000]:常规错误:1005无法创建表name_data_base.users(errno:150:150“外键约束)形成不正确形成”)
)
此错误仅在此关系中发生,因为我有更多的表格而且它没有给我一个问题。
这是两个表的代码:
员工表
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->foreignId('person_id')->references('id')->on('people');
$table->timestamps();
});
}
用户表
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->foreignId('employee_id')->references('id')->on('employees');
});
}
I have an error when placing a foreign key in the users table of laravel.
I have the Laravel users table, and I want to relate it to the employees table, which will have the personal data of the employees, but when I try to put the foreign key inside the users table, I get an error:
PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table name_data_base.users (errno: 150 "Foreign key constraint is incorrectly formed")")
This error only occurs in this relationship, since I have more tables and it does not give me a problem.
This is the code for the two tables:
employees table
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->foreignId('person_id')->references('id')->on('people');
$table->timestamps();
});
}
users table
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->foreignId('employee_id')->references('id')->on('employees');
});
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在员工表迁移文件架构:
中定义列
lightee_id
请记住
lightee_id
列类型,长度或无符号属性应该是同一用户表主键ID
。这是文档帮助:外键约束现在运行<代码> php工匠迁移,因此它将创建表
员工
和外键。You need to defined column
employee_id
in employees table migration file Schema:Remember
employee_id
column type, length or unsigned like properties should be same users table primary keyid
. Here is docs help:Foreign Key ConstraintsNow run
php artisan migrate
so it will create tableemployees
and foreign key too.