首页 > 解决方案 > 不能在新表 Laravel 5.8 上添加外键

问题描述

我有两个表,例如 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,但仍然错误。我正在使用-> 可为空的。但没用。有人能找到这个错误吗?

编辑 。这个错误:

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

标签: phplaravelforeign-keysmigration

解决方案


首先,创建角色表:

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

推荐阅读