【发布时间】:2021-12-24 07:49:59
【问题描述】:
我有一个 music_upload 表,它同时引用了专辑和用户表中的 album_id 和 user_id。 user_id 外键工作正常,是 album_id 外键喷出此错误
SQLSTATE[HY000]: General error: 1005 Can't create table `nightingalev2`.`music_uploads` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `music_uploads` add constraint `music_uploads_album_id_foreign` foreign key (`album_id`) references `albums` (`id`) on delete cascade)
这是我的album 表架构
Schema::create('albums', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('artist_id');
$table->string('name');
$table->timestamps();
$table->foreign('artist_id')->references('id')->on('artists');
});
这是我的music_uploads 架构
Schema::create('music_uploads', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('album_id');
$table->string('filename');
$table->string('extension');
$table->string('artistname')->nullable();
$table->string('albumname')->nullable();
$table->string('playtime')->nullable();
$table->string('genres')->nullable();
$table->integer('length')->nullable();
$table->string('filesize')->nullable();
$table->string('location')->nullable();
$table->string('thumbnail')->nullable();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('album_id')->references('id')->on('albums')->onDelete('cascade');
});
如果需要,这是我的 users 表架构
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
我从$table->id() 更改为$table->increment('id'),但它不起作用。把unsignedBitInteger改成integer()->unsigned()还是不行。
【问题讨论】:
-
错误似乎提到了
albums表。它的id列是否具有兼容的数据类型?为此目的,有符号整数和无符号整数不兼容。 -
我不明白你的问题。你能用外行的话说清楚吗?
-
有符号整数和无符号整数在外键关系方面不兼容。它们必须要么都签名,要么都未签名。但是根据您上面显示的代码,您似乎已经使它们都未签名。
id()快捷方式等同于bigIncrements('id')在 MySQL 用语中导致BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY。也许您之前使用不同的定义创建了它并且迁移正在使用它?我会去检查 MySQL 客户端并为每个表使用SHOW CREATE TABLE <name>来确认数据类型。 -
我签入了
albums表,在id列中显示id bigint(20) unsigned NOT NULL AUTO_INCREMENT -
@steven7mwesigwa 2021_04_03_134426_create_music_uploads_table.php 和 2021_11_11_195944_create_albums_table.php 这个?
标签: mysql laravel foreign-keys laravel-artisan laravel-migrations