【问题标题】:cant added foreign key on new table Laravel 5.8无法在新表 Laravel 5.8 上添加外键
【发布时间】:2019-10-15 16:22:59
【问题描述】:

我有两个表,例如 User 和 Roles 。我想在 Table Users 上添加外部 Roles_id 。

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('NIK',16);
        $table->string('nama');
        $table->string('email')->unique();
        $table->string('username');
        $table->string('password');
        $table->unsignedBigInteger('roles_id')->default(1);

        $table->timestamps();
        $table->softDeletes();

        $table->foreign('roles_id')->references('id')->on('roles');
    });
}

还有我的角色表

 public function up()
{
    Schema::create('roles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('roles');
        $table->timestamps();
    });
}

我没有捕捉到错过的代码,我使用 unsignedBigInteger,但仍然错误。 我正在使用 -> nullable 。但没有用。有人能找到这个错误吗?

编辑。这个错误:

SQLSTATE[HY000]:一般错误:1215 无法添加外键约束(SQL:alter table users 添加约束users_roles_id_foreign 外键(roles_id)引用rolesid))

【问题讨论】:

  • 角色迁移是否在用户表迁移之前运行?
  • 我先创建用户表。现在我有 2 个表 .users 和角色。我想让这个外国的。它的错误步骤?
  • 如果你想在users表中创建role_id作为foreign,必须已经创建了roles表。您可以做的是在用户迁移文件时间戳之前更改角色的迁移文件时间戳。
  • 好吧,看看我的步骤。我创建了用户表(在角色上没有 FK),现在我创建了角色表。(我现在有 2 个没有 FK 的表)。现在我在线程上添加了外国之类的。我运行 php artisan migrate 。并显示“Nothing to Migrate”
  • 如果我运行 migrate:fresh 它的错误就像在这个线程上一样

标签: php laravel foreign-keys migration


【解决方案1】:

首先,创建角色表:

 public function up(){
    Schema::create('roles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('roles');
        $table->timestamps();
    });
}

然后创建一个用户表:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('NIK',16);
        $table->string('nama');
        $table->string('email')->unique();
        $table->string('username');
        $table->string('password');

        $table->unsignedBigInteger('roles_id')->nullable();
        $table->foreign('roles_id')->references('id')->on('roles');

        $table->timestamps();
        $table->softDeletes();
    });
}

对于删除外键:

Schema::table('users', function (Blueprint $table) {
    $table->dropForeign('users_roles_id_foreign');
    $table->dropColumn('roles_id');
});

【讨论】:

  • 好的解决方案,但是如果它的这个项目已经准备好但是想像这样添加这个 FK,我是否还需要删除这个用户表并再次添加行 FK?
  • @Adhik Mulat 我已经更新了使用迁移删除外键的代码。现在检查
猜你喜欢
  • 2019-12-27
  • 2019-08-02
  • 1970-01-01
  • 2020-03-03
  • 1970-01-01
  • 2021-08-30
  • 2020-09-12
  • 2016-02-11
  • 2019-10-26
相关资源
最近更新 更多