ошибка при переносе с помощью внешнего ключа в laravel

#php #mysql #laravel #migration #laravel-8

#php #mysql #laravel #миграция #laravel-8

Вопрос:

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

/функция / up

 public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id('cat_id');
            $table->string('cat_name');
            $table->string('cat_desc');
            $table->string('cat_image');
            $table->timestamps();
        });



Schema::create('sellers', function (Blueprint $table) {
        $table->id('seller_id');
        $table->string('seller_name');
        $table->string('seller_desc');
        $table->string('seller_image');
        $table->timestamps();
    });

    Schema::create('products', function (Blueprint $table) {
        $table->id('prd_id');
        $table->string('prd_name');
        $table->string('prd_price');
        $table->string('prd_image');
        $table->string('prd_desc');
        $table->foreignId('product_cat_id')->constrained('categories');
        $table->foreignId('product_seller_id')->constrained('sellers');
        $table->boolean('prd_status');
        $table->timestamps();
    });

}
  

//ошибка

SQLSTATE[HY000]: Общая ошибка: 1005 Не удается создать таблицу ecommerce.products (ошибка: 150 «Неправильно сформировано ограничение внешнего ключа») (SQL: изменить таблицу products добавить ограничение products_product_cat_id_foreign внешний ключ (product_cat_id) ссылается на категории (id))

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

Комментарии:

1. Если у вас есть пользовательские имена идентификаторов, используйте более подробное объявление> $table-> foreign(‘user_id’)-> references(‘id’) -> on(‘users’);

Ответ №1:

 public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('cat_id')->unsigned();
            $table->string('cat_name');
            $table->string('cat_desc');
            $table->string('cat_image');
            $table->timestamps();
        });



Schema::create('sellers', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('seller_id')->unsigned();
        $table->string('seller_name');
        $table->string('seller_desc');
        $table->string('seller_image');
        $table->timestamps();
    });

    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('prd_id')->unsigned();
        $table->string('prd_name');
        $table->string('prd_price');
        $table->string('prd_image');
        $table->string('prd_desc');
        $table->foreignId('product_cat_id')->constrained('categories');
        $table->foreignId('product_seller_id')->constrained('sellers');
        $table->boolean('prd_status');
        $table->timestamps();
    });

}
  

Ответ №2:

Это связано с тем, что в вашем categories и sellers обоих таблицах первичный ключ отсутствует id , по умолчанию метод с ограничениями использует id первичный ключ as в качестве ссылки на внешний ключ, поэтому измените :

 $table->foreignId('product_cat_id')->constrained('categories');
$table->foreignId('product_seller_id')->constrained('sellers');
  

Для,

 $table->unsignedBigInteger('product_cat_id');
$table->foreign('product_cat_id')->references('cat_id')->on('categories');

$table->unsignedBigInteger('product_seller_id');
$table->foreign('product_seller_id')->references('seller_id')->on('sellers');
  

Если вы используете Model, то также определите свой первичный ключ в своей модели, например :

 protected $primaryKey = 'cat_id';