【问题标题】:General error 1215 while trying to make a foreign key within the same table, integer to integer尝试在同一个表中创建外键时出现一般错误 1215,整数到整数
【发布时间】:2023-03-27 07:55:02
【问题描述】:

我试图在同一个表中创建一个外键,但无论我测试什么都会出错。

在 Connection.php 第 647 行:

SQLSTATE[HY000]:一般错误:1215 无法添加外键约束(SQL:alter table trip_tags添加约束trip_tags_parent_foreign外键(parent)参考 ences trip_tags (id) 删除级联)

在 Connection.php 第 449 行:

SQLSTATE[HY000]:一般错误:1215 无法添加外键约束

这是我的代码

    Schema::create('trip_tags', function (Blueprint $table) {
        $table->engine = "InnoDB";
        $table->uuid('uuid')->unique();
        $table->integer('id')->unsigned();
        $table->string('name')->nullable();
        $table->integer('parent')->unsigned()->nullable();

        $table->timestamps();
    });

    Schema::table('trip_tags', function (Blueprint $table) {

        $table->foreign('parent')
            ->references('id')
            ->on('trip_tags')
            ->onDelete('cascade');
    });

我尝试将 parent 指向 id,两者都是无符号整数,我猜创建外键失败的原因是它们在某些方面不兼容,我不知道出了什么问题。

我试图将 parent 指向 uuid,但后来不得不将其设为字符串,这很有效。但是我必须让父指向 id 是整数,并且我不能让它迁移而没有我们的错误。

【问题讨论】:

  • uuid !== unsigned integer
  • 嗨开发者?我不是指向 uuid 列,只是指向名为 id 的列,知道会发生什么吗?
  • 哦,对不起。我的错。然后我相信发生错误是因为您在id 上没有索引。尝试添加unique()
  • 就是这样!你想发布一个我可以投票并选择正确的真实答案吗?
  • 乐于助人 :) 也将其作为答案发布

标签: laravel eloquent


【解决方案1】:

这是因为您的 id 列上没有索引。

在声明中添加->unique()

$table->integer('id')->unsigned()->unique();

【讨论】:

    猜你喜欢
    • 2020-03-09
    • 1970-01-01
    • 2021-09-28
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    • 2018-07-29
    相关资源
    最近更新 更多