Laravel 5.5 Eloquent - 可选择链接语句

时间:2018-01-22 22:03:06

标签: php laravel eloquent

我希望发生以下情况 - 如果字段与" all"不同,则按字段搜索。像这样:

//如果$ request [' field']!=' all'添加查询

if(isset($request['types'])) {
    $query = Offer::whereHas('types', function ($query) use ($request) {
        $typeArray = $request->get('types'); 
        $query->whereIn('type', $typeArray);
    });
}

if ($request['country'] != 'all') {
   query->where('country_id', $country);
}

最后,我想按顺序对结果进行排序和分页:

$offers = $query->orderBy('created_at', 'desc')->paginate(9);

有没有办法实现这个目标?如果我的问题不够清楚,请告诉我,我会编辑它并尝试更好地解释。

2 个答案:

答案 0 :(得分:4)

You can use eloquent when method to check conditions and append query. in when method you can check your conditions.

Offer::when(isset($request['types']), function($query) {
    $query->whereHas('types', function ($query) {
        $query->whereIn('type', request()->get('types'));
    });
})
->when(request()->country != 'all', function($query) {
    $query->where('country_id', request()->country);
})
->orderBy('created_at', 'desc')->paginate(9);

答案 1 :(得分:2)

你可以试试这个:

<?php

$query = Offer::where(function($q) use ($request){
    if ( !empty($request['country']) && is_numeric($request['country']) ) {
        $query->where('country_id', $request['country']);
    }

    if( !empty($request['types']) && is_array($request['types']) ) {
        $q->whereHas('types', function ($q) use ($request) {
            $typeArray = $request->get('types'); 
            $q->whereIn('type', $typeArray);
        });
    }
});


$offers = $query->orderBy('created_at', 'desc')->paginate(9);