D
D
Dmitry Yakovlev2018-05-14 12:28:04
Laravel
Dmitry Yakovlev, 2018-05-14 12:28:04

How to pull data (products, categories) through a pivot table in Laravel?

There are three tables products (products), categories (categories) and a pivot table connecting them .
One product can be in two categories at the same time. How to pull out all products that are in certain categories? That is, there is an array id category [1, 5, 31] and you need to pull out all the products that are in these 3 categories using it.
I wanted to do this:

categoryIds = [1, 4, 10];
 $products = Product::with(['categories' => function ($query) use ($categoryIds) {
            $query->whereIn('category_id', $categoryIds);
}])->paginate();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
mShpakov, 2018-05-14
@mShpakov

You have a relationship described in the category model
Get the category and by the name of the relationship (for example products) get all the products

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question