eloquent laravel 中预加载的条件

conditions in eager loading in eloquent laravel

我得到我的产品就是这个代码。我使用 with() 方法加载变化关系。 我有一些过滤器。但如果不存在任何变化,我会得到 Product.

我怎样才能只得到这个存在差异的产品?

$query = Product::with(array(
            'variations' => function($query) use($filters){
                if(isset($filters['price_start']) && !empty($filters['price_start'])){
                    $query->groupBy('id')->having(DB::raw('SUM(price_base + price_engraving)'), '>=', $filters['price_start']);
                }
                if(isset($filters['price_end']) && !empty($filters['price_end'])){
                    $query->groupBy('id')->having(DB::raw('SUM(price_base + price_engraving)'), '<=', $filters['price_end']);
                }

                if(isset($filters['q_magazine_start']) && !empty($filters['q_magazine_start'])){
                    $query->where('q_magazine', '>', $filters['q_magazine_start']);
                }
                if(isset($filters['q_magazine_end']) && !empty($filters['q_magazine_end'])){
                    $query->where('q_magazine', '<', $filters['q_magazine_end']);
                }

                return $query;
            }
        ))->whereIn('id', $productList);

要做到这一点,您必须再次执行几乎相同的操作,但使用 whereHas。由于闭包将完全相同,我们可以将其放在变量中以避免重复代码:

$filterClosure = function($query) use ($filters){
    if(isset($filters['price_start']) && !empty($filters['price_start'])){
        $query->groupBy('id')->having(DB::raw('SUM(price_base + price_engraving)'), '>=', $filters['price_start']);
    }
    if(isset($filters['price_end']) && !empty($filters['price_end'])){
        $query->groupBy('id')->having(DB::raw('SUM(price_base + price_engraving)'), '<=', $filters['price_end']);
    }

    if(isset($filters['q_magazine_start']) && !empty($filters['q_magazine_start'])){
        $query->where('q_magazine', '>', $filters['q_magazine_start']);
    }
    if(isset($filters['q_magazine_end']) && !empty($filters['q_magazine_end'])){
        $query->where('q_magazine', '<', $filters['q_magazine_end']);
    }
};

$query = Product::with(array('variations' => $filterClosure))
                ->whereHas('variations', $filterClosure)
                ->whereIn('id', $productList);

(顺便说一句,匿名函数的末尾不需要return $query

编辑

我们发现您需要将 groupBy 语句更改为 where

$filterClosure = function($query) use ($filters){
    if(isset($filters['price_start']) && !empty($filters['price_start'])){
        $query->where(DB::raw('price_base + price_engraving'), '>=', $filters['price_start']);
    }
    if(isset($filters['price_end']) && !empty($filters['price_end'])){
        $query->where(DB::raw('price_base + price_engraving'), '<=', $filters['price_end']);
    }

    // same code as above
};