Почему при миграции Laravel появляется ошибка ссылки? - PullRequest
1 голос
/ 11 июля 2020

Я создаю Laravel сайт электронной коммерции и следую этому руководству: https://www.youtube.com/watch?v=0lo7vzO1Fto&list=PLEhEHUEU3x5oPTli631ZX9cxl6cU_sDaR&index=20&t=417s

Я нахожусь в 18-м эпизоде, где создается таблица заказов. Я борюсь с первым разделом, создавая миграции. Есть два файла создания миграции:

  1. 2020_07_10_134530_create_orders_table. php (создает таблицу заказов)

  2. 2020_07_10_135517_create_order_product_table. php (создает таблицу сводная таблица для заказа и продукта)

Моя 'create_orders_table. php' выглядит так:

 public function up()
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->nullable();
            $table->foreign('user_id')->references('id')->on('users')
                ->onUpdate('cascade')->onDelete('set null');
            $table->string('billing_email')->nullable();
            $table->string('billing_name')->nullable();
            $table->string('billing_address')->nullable();
            $table->string('billing_city')->nullable();
            $table->string('billing_province')->nullable();
            $table->string('billing_postalcode')->nullable();
            $table->string('billing_phone')->nullable();
            $table->string('billing_name_on_card')->nullable();
            $table->integer('billing_discount')->default(0);
            $table->string('billing_discount_code')->nullable();
            $table->integer('billing_subtotal');
            $table->integer('billing_tax');
            $table->integer('billing_total');
            $table->string('payment_gateway')->default('stripe');
            $table->boolean('shipped')->default(false);
            $table->string('error')->nullable();
            $table->timestamps();
        });
    }

И моя 'create_order_product_table. php 'выглядит так:

public function up()
    {
        Schema::create('order_product', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('order_id')->unsigned()->nullable();
            $table->foreign('order_id')->references('id')
                ->on('orders')->onUpdate('cascade')->onDelete('set null');

            $table->integer('product_id')->unsigned()->nullable();
            $table->foreign('product_id')->references('id')
                ->on('iamlushes')->onUpdate('cascade')->onDelete('set null');

            $table->integer('quantity')->unsigned();
            $table->timestamps();
        });
    }

Когда я выполняю команду:

php artisan migrate

, я получаю следующую ошибку из терминала:

rosscurrie@Rosss-Air JanVal % php artisan migrate
Migrating: 2020_07_10_134530_create_orders_table

   Illuminate\Database\QueryException 

  SQLSTATE[HY000]: General error: 3780 Referencing column 'user_id' and referenced column 'id' in foreign key constraint 'orders_user_id_foreign' are incompatible. (SQL: alter table `orders` add constraint `orders_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete set null on update cascade)

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:671
    667|         // If an exception occurs when attempting to run a query, we'll format the error
    668|         // message to include the bindings with SQL, which will make this exception a
    669|         // lot more helpful to the developer instead of just the database's errors.
    670|         catch (Exception $e) {
  > 671|             throw new QueryException(
    672|                 $query, $this->prepareBindings($bindings), $e
    673|             );
    674|         }
    675| 

      +11 vendor frames 
  12  database/migrations/2020_07_10_134530_create_orders_table.php:38
      Illuminate\Support\Facades\Facade::__callStatic("create")

      +22 vendor frames 
  35  artisan:37
      Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))

Основная ошибка похоже:

SQLSTATE[HY000]: General error: 3780 Referencing column 'user_id' and referenced column 'id' in foreign key constraint 'orders_user_id_foreign' are incompatible. (SQL: alter table `orders` add constraint `orders_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete set null on update cascade)

И я думаю, что это относится к этой строке кода в моей миграции create_orders_table. php:

$table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('set null');

Я не уверен, как исправьте эту ошибку, вот моя миграция '2014_10_12_000000_create_users_table. php':

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

А вот мои таблицы продуктов '2020_06_16_124046_create_iamlush_table. php' миграция:

public function up()
    {
        Schema::create('iamlushes', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->string('fullname')->unique();
            $table->string('productLogo');
            $table->string('img')->unique();
            $table->text('description');
            $table->integer('price');
            $table->timestamps();
        });
    }

1 Ответ

3 голосов
/ 11 июля 2020

Вы используете $table->id(); при создании таблицы users. Он создает столбец типа unsinedBigInteger в базе данных, но вы ссылаетесь на этот столбец в таблице orders как на unsignedInteger, что создает конфликт.

Вы должны использовать unsignedBigInteger как тип столбца для user_id дюйм orders таблица, как показано ниже:

Schema::create('orders', function (Blueprint $table) {
        $table->increments('id');
        $table->bigInteger('user_id')->unsigned()->nullable();
        $table->foreign('user_id')->references('id')->on('users')
            ->onUpdate('cascade')->onDelete('set null');
        
        ....your code
});
...