【问题标题】:Optimizing Laravel's Eloquent models优化 Laravel 的 Eloquent 模型
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-27
    • 2021-07-22
    • 2017-10-07
    • 2020-09-24
    • 2014-02-05
    • 2015-03-12
    • 2015-08-10
    • 2016-02-26
    相关资源
    最近更新 更多