PHP Laravel按子级订购父级

时间:2016-12-18 14:05:28

标签: php laravel

我试图按照他们的号码排序两集。这是我的代码:

$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
            }]
        }
    }

1 个答案:

答案 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();