K
K
Konstantin2015-12-30 18:14:50
Laravel
Konstantin, 2015-12-30 18:14:50

How to optimize select query in Laravel5 (many-to-many)?

Hello. There are three tables: Products (id, name), Shops (id, name), Prices (id, price). In communication models
Products

public function price()
    {
        return $this->belongsToMany('App\Models\Price');
    }

The shops
public function price()
    {
        return $this->belongsToMany('App\Models\Price');
    }

Prices
public function shop()
    {
        return $this->belongsToMany('App\Models\Shop');
    }
    public function product()
    {
        return $this->belongsToMany('App\Models\Product');
    }

Added 2 pivot tables price-product and price_shop
I want to display all prices for one product in the form
Product store_name
-> price
.... store_name
-> price
To do this, I do
$product = Product::find($id);
$prices = $product->price;
foreach($prices as $price) {
$shops[$price->id][$price->price] = $price->shop[0]->name;
}
and pass the $shops array to wiev.
Everything works as it should. But, too many requests to the database. It turns out, how many goods, so many requests. Is it possible to change something to reduce the number of requests?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
D', 2015-12-30
@kostik34

$product = Product::with(['price', 'price.shop'])->where('id', $id)->first();

Load all data in groups (via IN).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question