Laravel Migration:错误代码:150“外键约束的格式不正确”

时间:2019-03-05 17:07:14

标签: laravel migration

我正在尝试执行此迁移:

用户:

Schema::create('comments', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('first_name');
            $table->string('last_name');
            $table->string('email')->unique();
            $table->string('avatar_url');
            $table->string('email_verified_at')->nullable();
            $table->string('password')->unique();
            $table->rememberToken();
            $table->timestamps();
            $table->softDeletes();
        });

文章:

Schema::create('articles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->text('title');
            $table->longText('body');
            $table->enum('state', ['draft', 'published']);
            $table->bigInteger('user_id')->unsigned();
            $table->timestamps();
            $table->softDeletes();
            $table->foreign('user_id')
                ->references('id')->on('users')
                ->onUpdate('cascade')->onDelete('cascade');
        });

但是当我迁移时,出现以下错误:

  

SQLSTATE [HY000]:常规错误:1005无法创建表blog_api#sql-2b70_7b(错误代码:150“外键约束为inc
    正确形成”)(SQL:在更新级联上删除级联上的更改表articles添加约束articles_user_id_foreign外键{user_id)引用users
id

我已经尝试将大整数和大增量重命名为简单的整数和增量,但没有成功。

1 个答案:

答案 0 :(得分:1)

应该有一个unassignedBigInteger,然后设置外键。

https://laravel.com/docs/5.8/migrations#foreign-key-constraints请检查官方文档

此外,

请注意迁移顺序。它从第一个文件一直到最新的文件,因此,如果您尝试为尚未创建的表设置外键,它将抛出错误。

例如

用户表与文章以及以下内容具有外键关系;

  • create_users_table
  • create_articles_table

由于尚未创建商品表格,因此您将无法进行分配。对于这种情况,我建议您在创建表的所有基本结构后使用“ add_foreign_keys_to_articles”。

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