在Laravel中对集合进行排序

时间:2019-02-19 15:39:59

标签: laravel controller laravel-5.7 laravel-controller

我的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同样如此。

1 个答案:

答案 0 :(得分:0)

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

$sortedData = $collection->sortBy('category', true);
相关问题