【发布时间】:2023-01-08 23:44:38
【问题描述】:
我希望特定员工负责其他员工,我正在尝试使用外键,即 head_id,它引用同一张表中的 id。但我收到此错误:
一般错误:1215 无法添加外键约束(SQL:alter table employees add constraint employees_head_id_foreign foreign key (head_id) references employees (id))。
我遇到了很多解决问题的办法,但都没有奏效。可能是什么原因?我的迁移:
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->foreignId('position_id')->constrained()->cascadeOnDelete();
$table->string('phone_number');
$table->date('recruitment_date');
$table->string('email')->unique();
$table->string('image_path')->nullable();
$table->string('payment');
$table->integer('head_id');
$table->timestamps();
$table->string('admin_created_id')->nullable();
$table->string('admin_updated_id')->nullable();
});
Schema::table('employees',function (Blueprint $table){
$table->foreign('head_id')->references('id')->on('employees');
});
}
【问题讨论】:
-
作为第一印象,约束键必须是同一类型,因为
id()生成一个bigIncrements类型,head_id归档也应该是bigIncrements。 -
对于您定义为
head_id的字段来限定来自同一表的键是没有意义的外国的.为什么需要head_id?外键指的是外表, 可以这么说。 -
@cengsemihsahin 我必须实施 softOnDelete 并在模型中创建关系,我相信这些事情只有使用外键才有可能,不是吗?
-
如前所述...
head_id必须与id的类型相同(无符号大整数);虽然我也会做到nullable
标签: php laravel migration laravel-9