【发布时间】:2023-01-20 17:29:42
【问题描述】:
我试图创建一个 cmets 表,该表将有一个外键 user_id,它引用用户表上的“ID”。但是每次我运行迁移时,我都会收到这个错误。
SQLSTATE[HY000]: 一般错误: 1005 无法创建表
9anime.comments(errno: 150 "外键约束的格式不正确") (SQL: alter tablecommentsadd constraintcomments user_id foreignforeign key (user_id) 在删除级联时引用users(id)我的用户迁移代码
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(); });我的 cmets 迁移文件
Schema::table('comments', function (Blueprint $table) { $table->unsignedInteger('user_id'); $table->foreign('user_id')->references('id')->on('users')->cascadeOnDelete(); });当我运行迁移时,出现该错误。我查看了我的代码,没有发现任何问题。 answer 建议将 user_id 设置为可为空。我这样做了,但它没有改变任何东西
【问题讨论】: