Laravel Eloquent Model Optimization

There are 3 MySQL tables in the database:

Products:

id | name

Product prices:

product_id | currency_id | price

Currency:

id | mark

And the Laravel Eloquent models look like this:

// Product.php
class Product extends Eloquent {

    protected $table = 'products';
    protected $primaryKey = 'id';

    public function prices(){
        return $this->hasMany('ProductPrice', 'product_id', 'id');
    }

}

// ProductPrice.php
class ProductPrice extends Eloquent {

    protected $table = 'product_prices';

    public function currency(){
        return $this->hasOne('Currency', 'id', 'currency_id');
    }

}

// Currency.php
class Currency extends Eloquent {

    protected $table = 'currencies';
    protected $primaryKey = 'id';

}

Now I need to show all products with all prices! And my code looks like this:

$products = Product::with('prices')->get();

foreach($products as $product){

    echo $product->name .'<br/>';

    foreach($product->prices as $price){
        echo $price->price .' '. $price->currency->mark .'<br/>';
    }

    echo '<hr/>';

}

The code works fine, but there are too many SQL queries (for each product it performs as many queries as there are currencies stored in the table). So, is there a way to optimize these models without using Query Builder?

Thank!

+4
source share
1 answer

You can try this to reduce the number of queries:

$products = Product::with('prices.currency')->get();

, , $price->currency->mark, .

+7

Source: https://habr.com/ru/post/1537572/


All Articles