【问题标题】:Laravel Migration : Errcode: 150 "Foreign key constraint is incorrectly formed"Laravel 迁移:Errcode:150“外键约束格式不正确”
【发布时间】:2019-07-27 05:35:03
【问题描述】:

我正在尝试执行此迁移:

用户:

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 Can't create table blog_api.#sql-2b70_7b (Errcode: 150 "Foreign key constraint is inc
正确形成”)(SQL:更改表articles添加约束articles_user_id_foreign外键(user_id)引用users<br>id)在更新级联上删除级联)

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

【问题讨论】:

标签: laravel migration


【解决方案1】:

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

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

另外,

请注意迁移顺序。它从第一个文件开始到最新的文件,因此如果您尝试为尚未创建的表设置外键,则会引发错误。

例如

Users表与文章有外键关系,如下所示;

  • 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');
            });

【讨论】:

    猜你喜欢
    • 2018-05-23
    • 2015-12-16
    • 2019-09-10
    • 2021-12-24
    • 1970-01-01
    • 2017-11-12
    • 2019-07-10
    • 2021-04-06
    • 2017-04-13
    相关资源
    最近更新 更多