【问题标题】:Eager loading sum from two pivot tables with Eloquent使用 Eloquent 从两个数据透视表中急切加载总和
【发布时间】:2015-08-19 17:01:10
【问题描述】:

我有一个 Part 实体,它与 OrderProject 具有多对多关系。数据透视表包含一个 quantity 字段,该字段可能具有正值或负值,通过将两个数据透视表的总和相加,对于特定部分,我得到当前库存。

我能够做到这一点,但遇到了 N+1 问题。而且我很难弄清楚如何通过急切加载来做到这一点。我读过这个post,但我不明白如何让它适应我的需要。

所以我正在寻找一种方法来在 Part 模型上提供一个急切的可加载库存属性,建议我如何实现这一点?

【问题讨论】:

    标签: laravel-5 eloquent pivot-table eager-loading


    【解决方案1】:

    post 的帮助下,我能够解决这个问题。这就是我所做的:

    零件模型

    创建两个关系orderPartsCountprojectPartsCount,添加属性calculatedStock对它们求和并提供一种简单的检索方式。

    public function orderPartsCount()
    {
        $a = $this->orders();
        $a1 = $a->selectRaw($a->getForeignKey() . ', sum(count) as stock')
                ->where('done', '>', 0)
                ->groupBy($a->getForeignKey()
            );
    
        return $a1;
    }
    
    public function projectPartsCount()
    {
        $b = $this->projects();
        $b1 = $b->selectRaw($b->getForeignKey() . ', sum(count) as stock')
                ->where('status', '>', 0)
                ->groupBy($b->getForeignKey()
            );
    
        return $b1;
    }
    
    public function getCalculatedStockAttribute()
    {
        $orders = $this->orderPartsCount->first() ? $this->orderPartsCount->first()->stock : 0;
        $projects = $this->projectPartsCount->first() ? $this->projectPartsCount->first()->stock : 0;
    
        // invert project parts, since they are listed as positive counts but shall reduce the stock
        return $orders + ( $projects * -1);
    }
    

    部分控制器

    在控制器中急切加载 orderPartsCountprojectPartsCount

    public function index()
    {
        return View::make('parts.index', [
            'parts' => Part::with('category', 'location', 'orderPartsCount', 'projectPartsCount')
                ->orderBy('description_no')
                ->paginate(100)
        ]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-11
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 2021-10-02
      • 1970-01-01
      • 2018-09-05
      • 1970-01-01
      相关资源
      最近更新 更多