簡體   English   中英

自引用多對多關系的遷移在 Laravel 中失敗,“外鍵約束形成不正確”

[英]Migration for self referencing many to many relation failing in Laravel with "Foreign key constraint is incorrectly formed"

我嘗試實現一個自我引用的多對多關系。 所以一個產品可以有一個或多個替代產品。 當我運行遷移時,出現此錯誤:

SQLSTATE[HY000]: General error: 1005 Can't create table xxx.productalternatives (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table productalternatives add constraint productalternatives_original_product_id_foreign foreign key (original_product_id) references products (id))

這就是我的遷移方式:

Schema::create('productalternatives', function (Blueprint $table) {
  $table->unsignedBigInteger('original_product_id'); 
  $table->unsignedBigInteger('alternate_product_id'); $table->timestamps(); 
  $table->foreign('original_product_id')->references('id')->on('products'); 
  $table->foreign('alternate_product_id')->references('id')->on('products');
});

任何想法是什么原因?

根據我的經驗,當您使用需要自引用外鍵的表時,您必須先創建表,然后(在新的“查詢”中)添加外鍵:

Schema::create('productalternatives', function (Blueprint $table) {
    $table->unsignedBigInteger('original_product_id'); 
    $table->unsignedBigInteger('alternate_product_id');
    $table->timestamps(); 
});

Schema::table('productalternatives', function (Blueprint $table) {
    $table->foreign('original_product_id')->references('id')->on('products'); 
    $table->foreign('alternate_product_id')->references('id')->on('products');
});

暫無
暫無

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

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