【问题标题】:Sorting collections in Laravel在 Laravel 中对集合进行排序
【发布时间】:2019-02-19 15:39:58
【问题描述】:

我的 Laravel 控制器和排序有点问题:

public function index()
{
    $achievements = Achievement::all();
    $news = News::all();
    $livingspaces = Livingspace::all();
    $therapies = Therapy::all();
    $events = Event::all();
    $collection = collect();

    foreach ($achievements as $achievement) {
        $collection->push($achievement);
    }
    foreach ($news as $new) {
        $collection->push($new);
    }
    foreach ($livingspaces as $livingspace) {
        $collection->push($livingspace);
    }
    foreach ($events as $event) {
        $collection->push($event);
    }
    foreach ($therapies as $therapy) {
        $collection->push($therapy);
    }

    $sortedData = $collection->sortBy('category')->sortByDesc('created_at');
    return response()->json([
        'sortedData' => $sortedData
    ], 200);
}

根本没有排序。它应该在为 Laravel 控制器创建新迁移时开箱即用的 created_at 时间戳中的数据之后进行排序。但我无法对数据进行排序。我认为这与将数据库中的数据直接推送到集合中有关,它根本不寻找“created_at”。它没有给出任何错误或任何东西,它只是没有做任何事情。 sortBy 也是如此。

【问题讨论】:

    标签: laravel controller laravel-5.7 laravel-controller


    【解决方案1】:

    sortByDesc 方法与 sortBy 方法具有相同的签名,但将以相反的顺序对集合进行排序。默认 sortBy 做升序操作。如果你想按降序排序:

    $sortedData = $collection->sortBy('category', true);
    

    【讨论】:

    • 未捕获(承诺中)错误:请求失败,状态码为 500
    猜你喜欢
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 2019-04-24
    相关资源
    最近更新 更多