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:
class Product extends Eloquent {
protected $table = 'products';
protected $primaryKey = 'id';
public function prices(){
return $this->hasMany('ProductPrice', 'product_id', 'id');
}
}
class ProductPrice extends Eloquent {
protected $table = 'product_prices';
public function currency(){
return $this->hasOne('Currency', 'id', 'currency_id');
}
}
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!
source
share