簡體   English   中英

MySQL 創建表:錯誤1005 errno:150“外鍵約束形成錯誤”

[英]MySQL create table: error 1005 errno: 150 “Foreign key constraint is incorrectly formed”

為什么 laravel 架構回復:

SQLSTATE[HY000]:一般錯誤:1005 無法創建表employee_management employees (errno: 150 "Foreign key constraint is wrongly forms") (SQL: alter table employees add constraint employees_city_id_foreign外鍵( city_id )引用city ( id ))

PDOException::("SQLSTATE[HY000]: 一般錯誤: 1005 無法創建表employee_management employees (errno: 150 "外鍵約束格式不正確")")

我的表:

  Schema::create('employees', function (Blueprint $table) {
            $table->increments('id', true);
            $table->string('lastname', 60);
            $table->string('firstname', 60);
            $table->string('middlename', 60);
            $table->string('address', 120);
            $table->integer('city_id')->unsigned();
            $table->integer('state_id')->unsigned();
            $table->integer('country_id')->unsigned();;
            $table->foreign('city_id')->references('id')->on('city');
            $table->foreign('state_id')->references('id')->on('state');
            $table->foreign('country_id')->references('id')->on('country');
            $table->char('zip', 10);
            $table->integer('age')->unsigned();
            $table->date('birthdate');
            $table->date('date_hired');
            $table->integer('department_id')->unsigned();
            $table->integer('division_id')->unsigned();
            // $table->integer('company_id')->unsigned();
            $table->foreign('department_id')->references('id')->on('department');
            $table->foreign('division_id')->references('id')->on('division');
            // $table->foreign('company_id')->references('id')->on('company');
            $table->string('picture', 60);
            $table->timestamps();
            $table->softDeletes();
        });

我的第二張城市表:

Schema::create('city', function (Blueprint $table) {
            $table->increments('id', true);
            $table->integer('state_id')->unsigned();
            $table->foreign('state_id')->references('id')->on('state');
            $table->string('name', 60);
            $table->timestamps();
            $table->softDeletes();
        });

PS我的Laravel版本是8.12

原因是您在創建city表之前嘗試遷移employee表,這很重要,因為您的employee表通過外鍵依賴於city表。

要解決這個問題,首先嘗試遷移城市表。

暫無
暫無

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

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