使用Laravel和收集按日期DESC对收集进行排序

bd1hkmkf  于 2022-12-27  发布在  其他
关注(0)|答案(1)|浏览(217)

我有一个集合,其中我以降序方式对"total"值进行排序。当"total"值相同时,我必须按降序日期对项目进行排序。

$collection->sortByDesc('total');

为了在总数相等时按降序日期对元素进行排序,我使用了sortsortByDesc,但元素仍然没有排序。

//First method
$collection->sortByDesc('created_at')->sortByDesc('total');

//Second method
$collection->->sort(function($a, $b){
   if($a->total === $b->total)
   {
      return strtotime($a->created_at) - strtotime($b->created_at);
   }
})->sortByDesc('total');

这两种选择对我都不起作用,我仍然得到相同的结果:

当结果如下时(当总值相等时,项目按下降日期排序):

我哪里做错了?
PS:先按"总计"再按"日期"排序对我没有帮助,因为"总计"值才是应该优先考虑的值。

xytpbqjk

xytpbqjk1#

sortByDesc将覆盖您在sort函数中完成的排序。
此外,strtotime($a->created_at) - strtotime($b->created_at)将按升序而不是降序对日期进行排序。
以下内容应该能给予您的需求:

$collection->sort(function ($a, $b) {
    if ($a->total === $b->total) {
        return strtotime($a->created_at) < strtotime($b->created_at);
    }

    return $a->total < $b->total;
});

最后,假设created_atupdated_atCarbon示例,您不需要使用strtotime

$a->created_at < $b->created_at

相关问题