我正在尝试运行php artisan migrate
以使用laravel创建我的mysql表。
我收到此错误:外键约束格式错误
用户表:
Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email', 150)->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); });
相册表:
Schema::create('albums', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->string('title'); $table->text('description'); $table->boolean('public'); $table->foreign('user_id')->references('id')->on('users')-> onDelete('SET NULL'); $table->timestamps(); });
图片表格:
Schema::create('images', function (Blueprint $table) { $table->increments('image_id'); $table->integer('user_id')->unsigned();; $table->string('image'); $table->integer('album_id')->unsigned();; $table->string('title'); $table->string('description'); $table->foreign('user_id')->references('id')->on('users')- >onDelete('SET NULL'); $table->foreign('album_id')->references('id')->on('albums')->onDelete('SET NULL'); $table->timestamps(); });
但是有错误:
SQLSTATE[HY000]: General error: 1005 Can't create table `photo_storage`.`#sql-2d70_10a` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `albums` add constraint `albums_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete SET NULL)`
答案 0 :(得分:0)
因为您有->onDelete('SET NULL')
,所以它期望字段user_id / album_id可为空。
像这样将图像和相册表中的user_id
和album_id
设为可空
$this->integer('field')->nullable()
然后重试