【问题标题】:Can't create foreign key on another table using ID of my users table [Foreign key constraint is incorrectly formed]无法使用我的用户表的 ID 在另一个表上创建外键 [外键约束的格式不正确]
【发布时间】:2023-01-20 17:29:42
【问题描述】:

我试图创建一个 cmets 表,该表将有一个外键 user_id,它引用用户表上的“ID”。但是每次我运行迁移时,我都会收到这个错误。

SQLSTATE[HY000]: 一般错误: 1005 无法创建表9anime.comments (errno: 150 "外键约束的格式不正确") (SQL: alter table comments add constraint comments user_id foreign foreign 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 设置为可为空。我这样做了,但它没有改变任何东西

【问题讨论】:

    标签: migration laravel-9


    【解决方案1】:

    我编辑了用户迁移文件,特别是这一行

    $table->id();

    $table->increments('id');

    然后运行我的迁移并且它有效

    【讨论】:

      猜你喜欢
      • 2020-07-05
      • 2023-02-03
      • 1970-01-01
      • 2018-02-04
      • 2023-02-14
      • 2021-05-26
      • 2019-01-05
      • 2014-11-20
      • 1970-01-01
      相关资源
      最近更新 更多