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

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

Schema::create('projects', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->timestamps();
});

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->foreignId('project_id')->constrained();
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

Schema::create('tasks', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained();
    $table->string('name');
    $table->timestamps();
});

当我 运行 php artisan migrate 仅创建用户 table 时,迁移过程停止...

SQLSTATE[HY000]: General error: 1005 Can't create table Projectname.users (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table users add constraint users_project_id_foreign foreign key (project_id) references projects (id))

您使用的 constrained() 往往会找到 table projectuser 而不是 projectsusers。在这种情况下,您需要在 constrained().

中指定 table 名称
Schema::create('projects', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->timestamps();
});

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->foreignId('project_id')->constrained('projects');
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

Schema::create('tasks', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained('users');
    $table->string('name');
    $table->timestamps();
});

您可以从 here

中了解更多

查找您的 migration 目录,您将看到所有迁移文件,例如 2014_10_12_000000_create_users_table

You are getting this error because your projects_create_table should be migrate before create_users_table file.

默认情况下,laravel 使每个迁移文件名都采用date_time 格式,如2014_10_12_000000_table_names.php 这样,所有文件都可以按顺序迁移。
因此,将您的 create_users_table 文件名更改为 date_time,以便可以在 projects_create_table 之后迁移,喜欢 :

2020_01_01_000000_create_projects_table.php
2020_01_01_000001_create_users_table.php

现在,如果你运行php artisan migrate,首先会创建projectstable,然后userstable。