如何从Laravel 5.2中附加各种查询的表中获取数据?

时间:2016-11-24 13:38:04

标签: laravel laravel-5 laravel-5.2

我试图为我的过滤器添加各种不同的查询,但问题是我的orWhere条件工作异常并且无论我的条件如何都给我结果。

我在下面添加了我的控制器:

public function earringsFilter(Request $request)
{
    if($request->isMethod('post')) {
        $data = array_filter($request->all());
        $filter = $data['filter'];
        $jewelleryEarringsData = Jwellery::select('id','name','price','msrp','metal_type','image_url','total_weight','image_2','image_3');
        $earrings = &$jewelleryEarringsData;
        $carat = array();
        $amount = array();
        $metal = array();
        if(isset($data['metal'])){
            $metal = $data['metal'];
            //$earrings->whereIn('metal_type', $metal);
            foreach($metal as $valk){
                $earrings->orWhere('metal_type', 'like', '%'.$valk.'%');
            }
        }
        if(isset($data['amount']['1']) && $data['amount']['1'] !=''){
            $amount = $data['amount'];
            $amt1 = $amount['0'];
            $amt2 = $amount['1'];
            $earrings->whereBetween('price',[$amt1,$amt2]);
        }
        if(isset($data['carat']['1']) && $data['carat']['1'] !=''){
            $carat = $data['carat'];
            $carat1 = $carat['0'];
            $carat2 = $carat['1'];
            $earrings->where('total_weight','>=',$carat1)->where('total_weight','<=',$carat2);
        } 
        $jewelleryEarringsData = $earrings->where('item_type', $filter)->get();
    }
}

所以我使用Laravel orWhere函数的代码给了我异常的结果。

2 个答案:

答案 0 :(得分:2)

请更改

$jewelleryEarringsData = Jwellery::select('id','name','price','msrp','metal_type','image_url','total_weight','image_2','image_3');

$jewelleryEarringsData = Jwellery::select('id','name','price','msrp','metal_type','image_url','total_weight','image_2','image_3')->get();

并将值重新分配给耳环变量。 希望这可以帮助你

答案 1 :(得分:0)

将您的代码更改为:

foreach ($metal as $valk){
    $earrings = $earrings->orWhere('metal_type', 'like', '%'.$valk.'%');
}