簡體   English   中英

Laravel 一般錯誤:1005 無法創建表`categories_products`(錯誤號:150“外鍵約束的格式不正確”)

[英]Laravel General error: 1005 Can't create table `categories_products` (errno: 150 "Foreign key constraint is incorrectly formed")

嘗試在 Laravel 中遷移並彈出此錯誤。 我認為錯誤可能是 bigInteger 類型,因為我在另一個相同的問題答案中發現。 請參閱將 bigInteger 更改為 bigIncrements,但我沒有遇到有關類型約束的另一個錯誤。

代碼

public function up()
    {
        Schema::create('categories_products', function (Blueprint $table) {
            $table->bigInteger('category_id')->unsigned()->index();
            $table->bigInteger('product_id')->unsigned()->index();

            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
        });
    }

錯誤

[Illuminate\Database\QueryException]
  SQLSTATE[HY000]: General error: 1005 Can't create table `categories_products` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `categori
  es_products` add constraint `categories_products_category_id_foreign` foreign key (`category_id`) references `categories` (`id`) on delete cascade)



  [Doctrine\DBAL\Driver\PDOException]
  SQLSTATE[HY000]: General error: 1005 Can't create table `categories_products` (errno: 150 "Foreign key constraint is incorrectly formed")



  [PDOException]
  SQLSTATE[HY000]: General error: 1005 Can't create table `categories_products` (errno: 150 "Foreign key constraint is incorrectly formed")

謝謝。

如果沒有看到關系的目標表上的列定義,很難給出明確的答案。 類型需要匹配。 因此,如果您在 id 字段中使用 bigIncrements(),那么unsignedBigInteger()bigInteger()->unsigned()都應該用作外鍵的類型,但是如果您使用increments作為 id 則外鍵需要是unsignedInteger()integer()->unsigned()

暫無
暫無

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

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