【问题标题】:Laravel migration throws foreign key exceptionLaravel 迁移抛出外键异常
【发布时间】:2019-10-22 19:07:47
【问题描述】:

我正在尝试编写具有外部关系的 laravel 数据库迁移。在数据库迁移期间抛出查询异常错误。

我厌倦了使用 laravel 规则迁移表,但是在迁移过程中它显示了意外错误。

用户表

    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name', 150);
        $table->string('email', 150)->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('phone', 150);
        $table->unsignedBigInteger('role_id');
        $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

角色表

    Schema::create('roles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('role_name',255);
        $table->longText('role_description',255);
        $table->integer('sort_order');
        $table->enum('status',['A','I','D'])->comment('A-active','I-inactive,D-delete'); 
        $table->enum('is_deleted',['Y','N'])->comment('Y-yes,N-no');
        $table->timestamps();
        $table->bigInteger('created_by');
        $table->bigInteger('updated_by')->default(0);
        $table->bigInteger('deleted_by')->default(0);
        $table->timestamp('deleted_at')->nullable();
    });

Illuminate\Database\QueryException : SQLSTATE[HY000]: 一般错误: 1215 无法添加外键约束(SQL:alter table jt_users 添加约束users_role_id_foreign外键(role_id) 在删除级联时引用jt_roles (id)

【问题讨论】:

  • 您似乎错过了在用户迁移中为role_id 定义列定义。迁移顺序也应该很重要......您必须确保角色迁移应该首先运行。

标签: php laravel migration


【解决方案1】:

您不能将外键添加到不存在的表中。在您的情况下,您尝试在创建 roles 表之前创建一个 role_id

在您的roles 表迁移中,一旦创建了roles 表,您将需要更新users 表:

Schema::create('roles', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('role_name',255);
    $table->longText('role_description',255);
    $table->integer('sort_order');
    $table->enum('status',['A','I','D'])->comment('A-active','I-inactive,D-delete'); 
    $table->enum('is_deleted',['Y','N'])->comment('Y-yes,N-no');
    $table->timestamps();
    $table->bigInteger('created_by');
    $table->bigInteger('updated_by')->default(0);
    $table->bigInteger('deleted_by')->default(0);
    $table->timestamp('deleted_at')->nullable();
});

Schema::table('users', function (Blueprint $table) {
    $table->unsignedBigInteger('role_id');
    $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});

注意:更改表格时使用Schema::table() 而不是Schema::create()

roles迁移的down()方法上,需要去掉外键和字段:

Schema::table('users', function (Blueprint $table) {
    $table->dropForeign(['role_id']);
    $table->dropColumn('role_id');
});

【讨论】:

    【解决方案2】:

    首先,必须迁移具有“主键”(用户)的表

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-05
      • 2016-06-06
      • 2019-09-23
      • 2017-02-26
      • 1970-01-01
      • 1970-01-01
      • 2014-04-23
      • 2020-06-02
      相关资源
      最近更新 更多