【发布时间】:2014-06-07 10:48:27
【问题描述】:
数据库中有3个MySQL表:
产品:
id | name
产品价格:
product_id | currency_id | price
货币:
id | mark
Laravel 的 Eloquent 模型如下所示:
// 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';
}
现在我需要显示所有价格的所有产品!我的代码如下所示:
$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/>';
}
代码运行良好,但是 SQL 查询太多(对于每个产品,它执行的查询与表中存储的货币数量一样多)。那么,有没有什么方法可以在不使用 Query Builder 的情况下优化这些模型呢?
谢谢!
【问题讨论】:
标签: php mysql laravel eloquent