سؤال

There are 3 MySQL tables in database:

Products:

id | name

Product prices:

product_id | currency_id | price

Currencies:

id | mark

And Laravel's 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, however there are too many SQL queries (for every product it performs as many queries as many currencies are stored in table). So, is there any way how to optimize these models without using Query Builder instead?

Thanks!

هل كانت مفيدة؟

المحلول

You may try this to reduce the queries:

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

This will eager load nested relationships, so each time you access $price->currency->mark it won't make a query for the related model.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top