G
G
golemico2017-07-30 20:55:34
Laravel
golemico, 2017-07-30 20:55:34

How to get products from a category?

I have three tables: product - products, catalog - product categories, product_catalog - table combining products and categories.
Tell me, how can I get products in the category I have chosen on laravel?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Semyon Beloglazov, 2017-07-30
@Batlab

In product, records have a field, what category do they belong to?
If not, then do it.

I
imdeveloper, 2017-07-30
@link_web

You need to use belongsToMany documentation

D
D3lphi, 2017-07-30
@D3lphi

Let's use relationships. Add a method to the Category model:

public function products()
{
    return $this->belongsToMany(Prdouct::class, 'product_catalog', 'category_id', 'product_id', 'id');
}

Where Product is the product model. 'product_catalog' - the so-called pivot table (a table combining products and categories). 'product_id' - product id in the pivot table, 'category_id' - category id in the pivot table.
Thus, you will be able to receive products belonging to a specific category like this:
Categoty::find(1)->products;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question