升序获取最后N个条目并排序

时间:2020-02-20 08:06:05

标签: laravel eloquent

我正在构建一个简单的消息框。每个消息都属于一个对话。我想做的是获取对话中的最后5条消息并按升序对其进行排序。

InboxController.php

public function messages($hashedId)
{
    $conversation = Conversation::where('hashed_id', $hashedId)->first();

    $messages = Message::where('conversation_id', $conversation->id)
        ->latest()
        ->take(5)
        ->get();

    $messages->orderBy('created_at','asc');


    return MessageResource::collection($messages);
}

错误

BadMethodCallException:方法Illuminate \ Database \ Eloquent \ Collection :: orderBy不存在。

2 个答案:

答案 0 :(得分:1)

使用sortBy函数。集合没有名为orderBy的函数。

$collection->sortBy('created_at');

参考:-https://laravel.com/docs/5.8/collections#method-sortby

答案 1 :(得分:1)

尝试

public function messages($hashedId)
{
    $conversation = Conversation::where('hashed_id', $hashedId)->first();

    $messages = Message::where('conversation_id', $conversation->id)
        ->take(5)
        ->orderBy('created_at','desc')
        ->get();

    return MessageResource::collection($messages);
}