在雄辩的laravel中急切加载的条件

时间:2015-01-29 15:41:17

标签: php laravel eloquent eager-loading

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

如何才能获得存在差异的产品?

$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);

1 个答案:

答案 0 :(得分:1)

要做到这一点,你必须再次使用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);

(顺便说一句,没有必要在匿名函数的末尾返回$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
};