英文:
Foreign key constraint is incorrectly formed (with inno db)
问题
当运行以下代码时:
Schema::create('files', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->id();
$table->string('path');
$table->timestamps();
});
Schema::create('file_users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->id();
$table->integer('file_id');
$table->foreign('file_id')->references('id')->on('files')->onDelete('cascade');
$table->mediumInteger('user_id');
$table->timestamps();
});
我收到以下错误信息:
SQLSTATE[HY000]: General error: 1005 无法创建表
atomes
.file_users
(错误号:150 "外键约束形式不正确")(SQL: alter tablefile_users
add constraintfile_users_file_id_foreign
foreign key (file_id
) referencesfiles
(id
) on delete cascade)
互联网上的答案都没有帮助到我。
我尝试将表类型更改为 myISAM
,但对我没有起作用。
英文:
When running:
Schema::create('files', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->id();
$table->string('path');
$table->timestamps();
});
Schema::create('file_users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->id();
$table->integer('file_id');
$table->foreign('file_id')->references('id')->on('files')->onDelete('cascade');
$table->mediumInteger('user_id');
$table->timestamps();
});
I'm getting error:
>SQLSTATE[HY000]: General error: 1005 Can't create table atomes
.file_users
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table file_users
add constraint file_users_file_id_foreign
foreign key (file_id
) references files
(id
) on delete cascade)
None of the internet answers helped me.
I tried changing the table types to myISAM
but that didn't work for me.
答案1
得分: 0
尝试这样做
Schema::create('file_users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->id();
$table->foreignId('file_id')->nullable(true)->constrained('files')->onUpdate('cascade')->onDelete('cascade');
$table->foreignId('user_id')->constrained('users');
$table->timestamps();
});
<details>
<summary>英文:</summary>
try this
Schema::create('file_users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->id();
$table->foreignId('file_id')->nullable(true)->constrained('files')->onUpdate('cascade')->onDelete('cascade');
$table->foreignId('user_id')->constrained('users');
$table->timestamps();
});
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论