我正在构建一个简单的消息框。每个消息都属于一个对话。我想做的是获取对话中的最后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不存在。
答案 0 :(得分:1)
使用sortBy
函数。集合没有名为orderBy的函数。
$collection->sortBy('created_at');
答案 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);
}