B
B
BonBon Slick2016-12-13 18:47:05
Laravel
BonBon Slick, 2016-12-13 18:47:05

Product = 1 category, category = many Laravel 5.3 products?

I figured out the joins 1:1, 10:10.
But 1:10 where 10:1 is something tight.
My example code:

// класс продукта
public function productCategory()
    {
       return $this->belongsTo('App\Category');
   }
// класс категории
 public function categoryProducts(){
        return $this->hasMany('App\Product');
    }
//  это вытянет все продукты, где category_id == текущий category_id
// Однако, обратной это не работет, dd($product->productCategory) в продукте, вернет null

How to get all products of a category, at the same time, get its category back from the product.
OneToMany, ManyToOne.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrzej Wielski, 2016-12-13
@BonBonSlick

In the case of categories, it is important to give the opportunity to link a product to several categories.
Start with the following code:
Migration

Schema::create('product_category', function (Blueprint $table) {
            $table->integer('product_id');
            $table->integer('category_id');
        });

Category Model
Product Model
return $this->belongsToMany('App\Category', 'product_category', 'product_id', 'category_id');

A
Alexander, 2016-12-13
@kentuck1213

public function productCategory()
    {
        return $this->hasOne('App\Category');
    }

public function categoryProducts(){
        return $this->hasMany('App\Product');
    }
// В котроллерах:
$category = Category::findOrFail(1);
dd($category->categoryProducts());

$product = Product::findOrFail(1);
dd($category->productCategory());

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question