【问题标题】:Cannot use foreign key to the same table in Laravel migration无法在 Laravel 迁移中对同一个表使用外键
【发布时间】: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


【解决方案1】:

确实是因为约束键必须是同一类型所以我不得不制作 head_id - 无符号大整数。现在可以了。

【讨论】:

    猜你喜欢
    • 2016-06-24
    • 2017-09-06
    • 1970-01-01
    • 2016-02-11
    • 2021-08-30
    • 1970-01-01
    • 2020-03-12
    • 1970-01-01
    相关资源
    最近更新 更多