【问题标题】:Laravel migration can not add foreign key in user tableLaravel 迁移不能在用户表中添加外键
【发布时间】:2019-11-05 02:00:00
【问题描述】:

我想在用户表中添加一个外键。一切似乎都很好,但我收到以下错误。

SQLSTATE[HY000]:一般错误:1005 无法创建表 electro_service.#sql-17d0_20 (err no: 150 "外键约束 格式不正确”)(SQL:alter table users 添加约束 users_role_id_foreign 外键 (role_id) 引用 rolesid)删除级联)。

用户

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('role_id');
        $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
        $table->string('name');
        $table->string('mobile');
        $table->string('code');
        $table->string('email')->unique();
        $table->tinyInteger('email_verified')->default(0);
        $table->string('email_verification_token', 128)->nullable();
        $table->string('image')->default('default.png');
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

角色

public function up()
{
    Schema::create('roles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->tinyInteger('role')->default(0);
        $table->string('slug')->unique();
        $table->timestamps();
    });
}

请告诉我如何修复它以及需要更改的地方。

【问题讨论】:

  • 角色表是否在用户表之前迁移?如果没有,那就去做并尝试
  • 可能问题是因为您为electro_service 运行迁移并希望在创建该表之前从用户那里获得外键。
  • @ViperTecPro 先生,如何在用户表之前迁移角色表?
  • @virtual 将用户迁移文件日期重命名为大于角色

标签: laravel laravel-5.8 laravel-migrations


【解决方案1】:

将用户迁移文件日期重命名为大于角色

示例:

2019_06_06_135936_create_roles_table
2019_06_06_135937_create_users_table

现在角色表将在用户迁移之前创建

【讨论】:

    猜你喜欢
    • 2014-03-31
    • 2021-06-09
    • 2020-01-23
    • 1970-01-01
    • 2016-02-11
    • 2020-03-13
    • 1970-01-01
    • 2021-08-30
    • 2018-04-01
    相关资源
    最近更新 更多