SQLSTATE [HY000]:常规错误:1005无法创建表ProjectName.users(错误号:150“外键约束格式不正确”)

时间:2020-08-06 20:13:51

标签: php mysql laravel laravel-7 laravel-migrations

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时,仅创建了users表,然后迁移过程停止了...

SQLSTATE [HY000]:常规错误:1005无法创建表 Projectnameusers(错误号:150“外键约束为 格式不正确”)(SQL:alter table users添加约束 users_project_id_foreign个外键(project_id)引用 projectsid))

2 个答案:

答案 0 :(得分:0)

您使用的constrained()倾向于找到表projectuser而不是projectsusers。在这种情况下,您需要在constrained()中指定表名称。

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

中学习更多内容

答案 1 :(得分:0)

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

您收到此错误消息是因为您的 projects_create_table 应该在 create_users_table 文件之前迁移。

默认情况下,laravel使用date_time格式(例如2014_10_12_000000_table_names.php)来制作每个迁移文件名,以便可以按顺序迁移所有文件。
因此,请使用date_time更改 create_users_table 文件名,以便可以在 projects_create_table 之后迁移,例如:

2020_01_01_000000_create_projects_table.php
2020_01_01_000001_create_users_table.php

现在,如果您运行php artisan migrate,将首先创建projects表,然后创建users表。