Порядок действий при создании отношения один-ко-многим в Laravel

Рейтинг: 1Ответов: 1Опубликовано: 10.07.2023

Не могу понять, как это делать правильно, ибо в phpmyadmin новых полей не добавляется. Имеется две модели - products и categories файл миграции для products

public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->timestamps();

            $table->string('name');
            $table->integer('price');
            $table->text('des');
            $table->foreign('category')->on('categories')->references('name');
        });
    }

categories

public function up(): void
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();

            $table->string('name');
        });
    }

Ответы

▲ 1Принят

Есть несколько вариантов для привязки двух таблиц, в миграции на laravel.

Вот первый метод.

public function up(): void
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->unsignedInteger('category_id');
        $table->string('name');
        $table->integer('price');
        $table->text('des');
        $table->foreign('category_id')->on('categories');
        $table->timestamps();
    });
}

А вот второй вариант.

public function up(): void
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->foreignId('category_id');
        $table->string('name');
        $table->integer('price');
        $table->text('des');
        $table->timestamps();
    });
}

Как то не понятно зачем привязать таблицы с колонкой name ?

Привязка таблиц делается числевыми колонками.

Посмотри более подробно в документации.

Ну а если хочешь что бы к одному продукту можно было привязать несколько категорий, тебе понадобиться еще одна таблица (product_categories).

1. Products

public function up(): void
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->integer('price');
        $table->text('des');
        $table->timestamps();
    });
}

2. Categories

public function up(): void
{
    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

3. Product Categories

Schema::create('product_categories', function (Blueprint $table) {
    $table->id();
    $table->foreignId('product_id')->constrained()->onDelete('cascade');
    $table->foreignId('category_id')->constrained()->onDelete('cascade');
    $table->timestamps();
});