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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With