簡體   English   中英

Laravel 7 遷移錯誤。 無法添加外鍵約束

[英]Laravel 7 migration error. Cannot add foreign key constraint

嘗試在 Laravel 7 中創建外鍵,但是當我使用artisan遷移表時,它會出錯

SQLSTATE[HY000]:一般錯誤:3780 外鍵約束“products_remote_id_foreign”中引用列“remote_id”和引用列“parent_id”不兼容。 (SQL:alter table 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。

編輯:

我更多地研究了外鍵,並在另一篇文章中找到了這個有用的答案。 外鍵需要具有唯一約束或為主鍵。 由於您的remote_id列引用的parent_id既不是主鍵也不是唯一約束,因此您會收到此錯誤。

另一個問題中給出的添加唯一約束的解決方案正在運行此命令(針對您的表進行了修改):

alter table categories add constraint uq1 unique (parent_id);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM