【问题标题】:Problem with data sorting, sortBy function数据排序问题,sortBy函数
【发布时间】:2019-06-25 20:32:21
【问题描述】:

抱歉,这个问题可能很愚蠢,但我对排序结果有疑问,我只想按 updated_at->data 降序排序结果,所以最新记录在最上面

public function boostsRequest()
{
    $boosts = Cache::remember('boosts_all', 30, function () {
        $raw = Boost::where('status', 3)->where('hidden', false)->with('screenshot')->get();

        $raw->transform(function ($boost) {
            return [
                'currentdivision' => $boost->currentdivision,
                'desireddivision' => $boost->desireddivision,
                'wins' => $boost->wins,
                'type' => $boost->type,
                'screenshot' => optional($boost->screenshot)->url,
                'updated_at' => $boost->updated_at,
            ];
        });

        $raw = $raw->sortBy(function ($boost) {
            return strtotime($boost->updated_at->date);
        });            

        return $raw;
    });

    return $boosts;
}

通常,函数调用的结果是一个 JSON 表,其中填充了具有以下结构的对象:

{"currentdivision":"12","desireddivision":"16","wins":null,"type":"division","screenshot":"https:\/\/ucarecdn.com\/86c6d345-1a7f-4af4-8005-175ee235ccd8\/","updated_at":{"date":"2016-11-03 11:11:26.000000","timezone_type":3,"timezone":"UTC"}}

我想要一个按字段updated_at-> date 排序的对象表,降序排列,因此最近更新的对象为第一

【问题讨论】:

  • 究竟是什么问题?你有错误吗?还是排序不起作用?
  • 刚刚更新了我的帖子

标签: laravel sorting


【解决方案1】:

updated_at 值不是对象,只删除->date 部分,只需要这段代码。

return strtotime($boost->updated_at);

提示:有时当我们怀疑值的表示方式或 php 函数在表记录上的行为方式时,我们可以使用 tinker :D。

【讨论】:

    【解决方案2】:

    只需在 eloquent 请求中按更新时间对集合进行排序:

    $raw = Boost::where('status', 3)->where('hidden', false)->with('screenshot')->orderBy('updated_at')->get();
    

    updated_at 值中,您确定它存在于数据库中。不需要关闭。

    【讨论】:

      猜你喜欢
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      • 2019-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多