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无法创建表
Projectname
。users
(错误号:150“外键约束为 格式不正确”)(SQL:alter tableusers
添加约束users_project_id_foreign
个外键(project_id
)引用projects
(id
))
答案 0 :(得分:0)
您使用的constrained()
倾向于找到表project
或user
而不是projects
或users
。在这种情况下,您需要在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
表。