Многие-ко-Многим
Last updated
Last updated
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->text('description')->nullable();
$table->timestamps();
});
}
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->float('price');
$table->text('description')->nullable();
$table->timestamps();
});
}
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');
});
}
Product может принадлежать многим Category
Category может принадлежать многим Product
class Product extends Model
{
public function categories()
{
return $this->belongsToMany(Category::class);
// return $this->belongsToMany(Category::class, 'category_product', 'product_id', 'category_id');
}
}
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);