Почему мой внешний ключ не работает при миграции - Laravel - PullRequest
0 голосов
/ 24 октября 2019

Я пытаюсь выполнить новую миграцию базы данных в Laravel, но кажется, что она застряла при создании внешнего ключа. Он генерирует следующую ошибку.

errno: 150 "Foreign key constraint is incorrectly formed"

Я уже нашел этот пост Миграция Laravel (ошибка: 150 "Неправильно сформировано ограничение внешнего ключа") , но я использовал bigIncrements с unsignedBigInteger, так чтоработать правильно? И я также делал то же самое в предыдущем проекте, и он работал просто отлично.

Dropped all tables successfully.
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table (0.42 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table (1.05 seconds)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated:  2019_08_19_000000_create_failed_jobs_table (0.65 seconds)
Migrating: 2019_10_23_110756_create_campaigns_table

Кажется, он застрял на $table->foreign('game_id')->references('id')->on('games'); в таблице кампаний, что странно, потому что он делает $table->foreign('user_id')->references('id')->on('users'); простоштраф? Когда я закомментирую внешний ключ game_id, он прекрасно переносит все таблицы? Может быть потому, что игровой стол еще не создан? И как бы я решил это?

Миграция игр

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateGamesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('games', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('games');
    }
}

Миграция кампании

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCampaignsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('campaigns', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->longText('settings');
            $table->longText('preview_settings');
            $table->text("description")->nullable();
            $table->enum('type', ['desktop', 'appstore', 'facebook', 'messenger', 'playstore', 'mobile']);
            $table->enum('published', ['Draft', 'Ready', 'Live']);
            $table->datetime("start_time")->nullable();
            $table->datetime("end_time")->nullable();
            $table->timestamps();
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('game_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->foreign('game_id')->references('id')->on('games');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('campaigns');
    }
}

Миграция пользователя

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Ответы [ 2 ]

0 голосов
/ 24 октября 2019

Поскольку таблица кампаний создана, но таблица игр еще не создана.

Миграция работает по порядку.

Смотри список, игры при миграции не отображаются;

Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table (0.42 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table (1.05 seconds)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated:  2019_08_19_000000_create_failed_jobs_table (0.65 seconds)
Migrating: 2019_10_23_110756_create_campaigns_table

Можете ли выотредактируйте и попробуйте коды следующим образом:

Миграция игр;

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateGamesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('games', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->timestamps();
        });

    Schema::table('campaigns', function(Blueprint $table)
    {
        $table->foreign('game_id')->references('id')->on('games');
    });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('games');
    }
}

Миграция кампании;

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCampaignsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('campaigns', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->longText('settings');
            $table->longText('preview_settings');
            $table->text("description")->nullable();
            $table->enum('type', ['desktop', 'appstore', 'facebook', 'messenger', 'playstore', 'mobile']);
            $table->enum('published', ['Draft', 'Ready', 'Live']);
            $table->datetime("start_time")->nullable();
            $table->datetime("end_time")->nullable();
            $table->timestamps();
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('game_id');
            $table->foreign('user_id')->references('id')->on('users');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('campaigns');
    }
}
0 голосов
/ 24 октября 2019
$table->bigInteger('user_id')->unsigned();
$table->bigInteger('game_id')->unsigned();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...