我正在尝试构建一个laravel查询,该查询应按以下方式在名为“ competition_type”的列中对值进行排序:“ ATP-SINGLES”,“ WTA-SINGLES”,“ CHALLENGER MEN-SINGLES”,“ CHALLENGER WOMEN-SINGLES” ','ITF MEN-SINGLES','ITF WOMEN-SINGLES',但我尝试了此查询,但确实有效...
$matches = Match::select()
->where('date', $date)->where('pick_score', '<>', '0');
$matches = $matches->orderBy('hour', 'ASC');
$matches = $matches->orderBy(Match::raw("case when competition_type in ('ATP - SINGLES', 'WTA - SINGLES") then -1 else competition_type end, competition_type'));
我应该进行哪些更改才能使其正常工作?
答案 0 :(得分:0)
您可以通过以下查询将其归档,使用Eloquent / Collection中可用的transform方法可以使代码更具可读性。
Match::select()
->whereDate($date)
->where('pick_score', '<>', '0')
->orderBy('hour')
->transform(function ($match) {
if(
$match->competition_type == "ATP - SINGLES"
or
$match->competition_type == "WTA - SINGLES"
){
$match->competition_type = -1;
}else{
$match->competition_type = 'competition_type';
}
return $match;
})
->sortBy('competition_type')
注意:您可以在laravel中使用动态Where条件, whereFiledName(value)
答案 1 :(得分:0)
"case when competition_type in ('ATP - SINGLES', 'WTA - SINGLES') then -1 else competition_type end, competition_type"
将Match::raw()
更改为DB::raw()
您有两个orderBy
,您需要将其设置为一个,如果要先按hour
进行订购,然后再按competition_type
进行订购,则需要这样做:
orderBy('hour', DB::raw("CASE WHEN competition_type IN ('ATP - SINGLES', 'WTA - SINGLES') then -1 ELSE competition_type END"))
因此您的代码将如下所示:
$matches = Match::where('date', $date)
->where('pick_score', '<>', '0');
$matches = $matches->orderBy('hour', DB::raw("CASE WHEN
competition_type IN ('ATP - SINGLES', 'WTA - SINGLES') then -1
ELSE competition_type END"))
// you can remove case when from select, I just select it out for you can proofread better
->select('match.*', DB::raw("CASE WHEN
competition_type IN ('ATP - SINGLES', 'WTA - SINGLES') then -1
ELSE competition_type END"));