Многие-ко-Многим

Миграции для моделей
create-categories-table
public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->text('description')->nullable();
            $table->timestamps();
        });
    }
create-products-table
public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->float('price');
            $table->text('description')->nullable();
            $table->timestamps();
        });
    }
create-category_product-table
public function up()
    {
        Schema::create('category_product', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('category_id');
            $table->unsignedBigInteger('product_id');
            $table->foreign('category_id')->references('id')->on('categories');
            $table->foreign('product_id')->references('id')->on('products');
        });
    }

Пример отношения Многие-ко-Многим Category и Product

  • Product может принадлежать многим Category

  • Category может принадлежать многим Product

app/Models/Product.php
class Product extends Model
{
    public function categories()
    {
        return $this->belongsToMany(Category::class);
        // return $this->belongsToMany(Category::class, 'category_product', 'product_id', 'category_id');
    }
}
app/Models/Category.php
class Category extends Model
{
    public function products()
    {
        return $this->belongsToMany(Product::class);
        // return $this->belongsToMany(Product::class, 'category_product', 'category_id', 'product_id');
    }
}

Получение данных «Многие-ко-Многим»

// получаем все продукты которые связаны с этой категорией
$category = Category::find(1);
$category->products;
// получаем категории которые связаны с этим продуктом
$product = Product::find(1);
$product->categories;

Создание отношения «Многие-ко-Многим»

// создаём категории
$category = new Category(['name' => 'phones']);
$category->save();
$category2 = new Category(['name' => 'smartphones']);
$category2->save();

// создаём продукт
$product = new Product([
    'name'  =>  'Home Brixton Faux Leather Armchair',
    'price' =>  199.99,
]);
// сохраняем его в БД
$product->save();
// выбираем категрии с айди 1 и 2
$categories = Category::find([1,2]);
// присоединяем продукт к категориям
$product->categories()->attach($categories);
$product->categories()->attach($product);
$category->products()->attach($category);

Оба метода делают одно и то же
$product->categories()->syc($product);
делает то же самое но без дубликатов

Удаление отношения «Многие-ко-Многим»

$category = Category::find(2);
$product = Product::find(1);
// удаляем отношение категории 2 с продуктом 1
$product->categories()->detach($category);

Last updated