【问题标题】:Foreign key constraint is incorrectly formed - MariaDB & Laravel外键约束的格式不正确 - MariaDB & Laravel
【发布时间】:2019-11-02 05:53:07
【问题描述】:

我在 laravel 5.8 中运行数据库迁移,我收到以下错误:

Illuminate\Database\QueryException : SQLSTATE[HY000]: 一般错误: 1005 无法创建表cartorque.likes (errno: 150 "外键约束格式不正确") (SQL: alter table @987654323 @添加约束likes_ post_id_foreign外键(post_id)引用postsid)在更新级联上删除级联)

这是我的表的设置方式

User Table:
    Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
Posts Table
Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->timestamps();
            $table->string('title', 500);
            $table->longText('content');
            $table->tinyInteger('privacy')->default('0');
            $table->string('location', 250);
            $table->bigInteger('longitude');
            $table->bigInteger('latitude');
            $table->bigInteger('user_id')->unsigned()->index();
            $table->string('slug', 250);
        });

        Schema::table('posts', function (Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('users')
                ->onDelete('cascade')
                ->onUpdate('cascade');
        });
Likes Table
Schema::create('likes', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->timestamps();
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('post_id');
            $table->boolean('like');
        });

        Schema::table('likes', function (Blueprint $table) {
            $table->foreign('post_id')->references('id')->on('posts')
                ->onDelete('cascade')
                ->onUpdate('cascade');
        });

        Schema::table('likes', function (Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('users')
                ->onDelete('cascade')
                ->onUpdate('cascade');
        });

Likes 表有 2 个外键 user_id 和 post_id。它在 user_id 上工作正常,但我在 post_id 列上得到错误

【问题讨论】:

    标签: database laravel database-migration


    【解决方案1】:

    发现了问题,它是未创建的帖子表。这是因为迁移文件的顺序。 likes 外键创建是在创建 posts 表之前发生的。我更改了迁移文件的顺序。

    【讨论】:

      猜你喜欢
      • 2017-05-29
      • 2019-09-15
      • 1970-01-01
      • 2017-10-03
      • 2019-07-25
      • 2017-10-04
      • 2019-03-08
      • 2018-02-19
      • 2021-05-26
      相关资源
      最近更新 更多