微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Laravel 7迁移错误无法添加外键约束

如何解决Laravel 7迁移错误无法添加外键约束

尝试在Laravel 7中创建外键,但是当我使用artisan迁移表时会出现错误

sqlSTATE [HY000]:常规错误:3780外键约束'products_remote_id_foreign'中的引用列'remote_id'和引用列'parent_id'不兼容。 (sql:在删除级联上,更改表products添加约束products_remote_id_foreign外键(remote_id)引用categoriesparent_id

我的类别表

Schema::create('categories',function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('parent_id');
            $table->tinyinteger('depth');
            $table->string('name');
            $table->string('slug');
            $table->text('description');
            $table->timestamp('created_at')->useCurrent();
            $table->timestamp('updated_at')->default(DB::raw('NULL ON UPDATE CURRENT_TIMESTAMP'))->nullable();
        });

我的产品表

Schema::create('products',function (Blueprint $table) {
            $table->id();

            $table->unsignedBigInteger('remote_id');
            $table->foreign('remote_id')->references('parent_id')->on('categories')->onDelete('cascade');
            
            $table->unsignedBigInteger('category_id');
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');

            $table->string('name');
            $table->text('description');
            $table->integer('price');
            $table->tinyinteger('status')->default(1);
            $table->integer('qty');
            $table->string('barcode')->nullable();
            $table->string('image');
            $table->text('images')->nullable();
            $table->timestamp('created_at')->useCurrent();
            $table->timestamp('updated_at')->default(DB::raw('NULL ON UPDATE CURRENT_TIMESTAMP'))->nullable();
        });

关于我做错了什么的任何想法? 感谢您的帮助!

解决方法

如aynber所述,要使外键兼容,它们必须是同一类型。您在产品表中的remote_id unsignedBigInteger ,而您试图在类别表中引用的键parent_id integer 。要解决此问题,请将产品表中的category_id更改为整数,或将类别表中的parent_id更改为unsignedBigInteger。

编辑:

我进一步研究了外键,并在另一篇文章中找到了this有用的答案。外键必须具有唯一约束或为主键。由于您的remote_id列所引用的parent_id既不是主键也不是唯一约束,因此会出现此错误。

另一个问题中添加唯一约束的解决方案正在运行此命令(已针对您的表进行了修改):

alter table categories add constraint uq1 unique (parent_id);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。