Laravel 使用外键进行迁移失败

Laravel make migration with foreign key failed

我有一个名为 Partner 的项目

我需要创建 developers table 和另外两个 tables branchesprojects

并且每个开发人员都有很多 b运行ches 并且有很多项目

所以我创建了这个迁移文件:

开发人员

public function up()
{
    Schema::create('developers', function (Blueprint $table) {
        $table->id();
        $table->string('company_name', 100);
        $table->string('responsible_name', 100);
        $table->string('email', 100);
        $table->string('phone', 100);
        $table->string('hotline', 100)->nullable();
        $table->timestamps();
    });
}

B运行切

public function up()
{
    Schema::create('branches', function (Blueprint $table) {
        $table->id();
        $table->integer('developer_id')->unsigned();
        $table->string('name', 100);
        $table->string('address', 100);
        $table->string('location', 100);
        $table->string('phone', 100);
        $table->timestamps();
        $table->foreign('developer_id')->references('id')->on('developers')->onDelete('cascade');
    });
}

项目

public function up()
{
    Schema::create('projects', function (Blueprint $table) {
        $table->id();
        $table->integer('developer_id')->unsigned();
        $table->string('name', 100);
        $table->string('type', 100);
        $table->string('address', 100);
        $table->string('location', 100);
        $table->string('availability', 100);
        $table->text('payment_plan');
        $table->string('brochure', 100)->nullable();
        $table->timestamps();
        $table->foreign('developer_id')->references('id')->on('developers')->onDelete('cascade');
    });
}

但是当我 运行 php artisan migrate 我得到这个错误

SQLSTATE[HY000]: General error: 1005 Can't create table `partner`.`branches` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `branches` add constraint `branches_developer_id_foreign` foreign key (`developer_id`) references `developers` (`id`) on delete cascade)

外键的形式有什么问题?

您可以在没有预定义字段的情况下在迁移中使用外键:

$table->foreignId('developer_id')->constrained('developers')->onDelete('cascade');

并删除这一行:

$table->integer('developer_id')->unsigned();