我试图按照他们的号码排序两集。这是我的代码:
$neededEpisodes = SharedMethods::getAround($numbers);
$nearEpisodes = TheEpisode::where("seriesID", $seriesID)->whereHas('TheNumbers', function($q) use($neededEpisodes) {
$q->whereIn('episodeNumber', $neededEpisodes);
});
echo $nearEpisodes->get()->toJson();
这将输出以下结果:
"nearEpisodes": [{
"id": 16445,
"the_numbers": [{
"episodeID": 16445,
"episodeNumber": 208
}]
}, {
"id": 16487,
"the_numbers": [{
"episodeID": 16487,
"episodeNumber": 210
},{
"episodeID": 16487,
"episodeNumber": 211
}]
}]
问题是The_Numbers顺序应该相反,从210,211开始,然后是208。
所以我的预期输出应该是id:16487然后是16445。
我应该如何构建雄辩的查询来实现这一目标?
nearEpisodes": {
"1": {
"id": 16503,
"episodeTitle": "Episodul 183",
"the_numbers": [{
"episodeID": 16503,
"episodeNumber": 183
}]
},
"0": {
"id": 16190,
"episodeTitle": "Episodul 181",
"the_numbers": [{
"episodeID": 16190,
"episodeNumber": 181
}]
}
}
答案 0 :(得分:1)
您可以使用sortByDesc
收集方法:
$nearEpisodes = TheEpisode::where("seriesID", $seriesID)
->whereHas('TheNumbers', function($q) use($neededEpisodes) {
$q->whereIn('episodeNumber', $neededEpisodes);
})
->with(['TheNumbers' => function($q) use($neededEpisodes) {
$q->whereIn('episodeNumber', $neededEpisodes);
}])
->get();
$nearEpisodes = $nearEpisodes->sortByDesc(function ($item) {
return $item->the_numbers->max('episodeNumber');
})->values();
echo $nearEpisodes->toJson();