【问题标题】:Eager Loading with Aggregate Functions使用聚合函数进行急切加载
【发布时间】:2017-02-07 00:39:47
【问题描述】:

我正在尝试使用 Laravel 的 Eager loading 来解决我商店中的 N+1 查询问题。

-一个产品有很多变体,每个变体都有一个价格

-商店页面列出所有产品及其价格。活跃成员会看到折扣价,因此会看到 price() 和 regularPrice()。

-我相信 scopeRegularPrice() 中的 min() 和 max() 没有被正确加载。

是否有使用聚合函数进行预加载的最佳做法?

产品型号

控制器

刀片输出 查询结果(通过 Blackfire 调试工具)

【问题讨论】:

    标签: sql laravel eloquent laravel-5.3 eager-loading


    【解决方案1】:

    您的本地范围应该返回一些东西。所以添加

    public function scopeRegularPrice() {
        ...
        return 'something'
    }
    

    如果您已经退货了,那么抱歉。我在您的代码中看不到任何返回语句。

    【讨论】:

    • 我上传了带有返回值的完整函数。为了避免混淆,我早先把它切断了。 (我认为问题的出现是因为我在 scopeRegularPrice() 内调用 min() 和 max())
    • scopeRegularPrice() 返回的是什么?数组?当你比较时,试着做if ( $product->price != $product->regularPrice() )。价格没有括号。除非price 是一个函数而不是一个属性。
    【解决方案2】:

    范围应该以任何方式返回 Querybuilder;

    您最好将其作为产品型号的常规价格;

    使变化关系按价格排序。 并将此方法添加到产品类中。

     public function getRegularPriceAttribute() {
    
           $variations = $this->variations;
           // Get the live variations by where on collection , not DB query.
           $liveVaries = $variations->where('live', true)->all();
          // the first is the cheapest because you the variations relation should be orderBy('price')
           if (! empty($liveVaries)) return [first($liveVaries)->price, last($liveVaries)->price];
    
           return [first($variations)->price, last($variations)->price];}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      • 1970-01-01
      • 2011-12-03
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      相关资源
      最近更新 更多