не могу добавить внешний ключ на новую таблицу Laravel 5.8 - PullRequest
0 голосов
/ 30 мая 2019

У меня есть две таблицы, такие как Пользователь и Роли.я хочу добавить иностранный 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 , но ошибка по-прежнему.я использую -> обнуляемый .но не сработало.Может ли кто-нибудь найти эту ошибку?

edit.эта ошибка:

SQLSTATE [HY000]: общая ошибка: 1215 Невозможно добавить ограничение внешнего ключа (SQL: изменить таблицу users добавить ограничение users_roles_id_foreign ссылки на внешний ключ (roles_id) roles(id))

1 Ответ

0 голосов
/ 30 мая 2019

Сначала создайте таблицу ролей:

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