MySQL 创建表:错误 1005 errno: 150 “外键约束的格式不正确”

时间:2021-05-16 17:48:20

标签: mysql laravel

为什么要回复 Laravel 架构:

<块引用>

SQLSTATE[HY000]:一般错误:1005 无法创建表 employee_management.employees (errno: 150 "外键约束 格式不正确”)(SQL:alter table employees 添加约束 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();
        });

附言我的 Laravel 版本是 8.12

1 个答案:

答案 0 :(得分:1)

原因是您在创建 employee 表之前尝试迁移 city 表,这很重要,因为您的 employee 表通过外键依赖于 city 表。< /p>

要解决这个问题,首先尝试迁移城市表。