优化Laravel';s难以捉摸的模特


Optimizing Laravel's Eloquent models

数据库中有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查询太多(对于每种产品,它执行的查询数量与表中存储的货币数量一样多)。那么,有什么方法可以在不使用查询生成器的情况下优化这些模型吗?

谢谢!

您可以尝试这样做来减少查询:

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

这将急切地加载嵌套关系,因此每次访问$price->currency->mark时,它都不会查询相关模型。