php - 如何在 laravel 的 latest() 中使用 ASC 和 DESC
问题描述
$thread = Thread::with(['messages' => function($q) {
$q->with('detail_per_user');
$q->with('post');
$q->with(['forum' => function($sq) {
$sq->with(['forum_messages' => function($isq) {
$isq->orderBy('id', 'ASC');
}]);
}]);
$q->with('attachments');
$q->orderBy('id', 'ASC');
$q->latest();
$q->take(20);
}])->with('users.user_details:id,avtar,name,parent_id,generated_id')->where('id', '=', $thread_id)->get()->toArray();
ASc 和 DSC 不能在最新版本中工作。我需要按 ASC 顺序获取最新的 20 条消息。结果按 desc 顺序排列。
解决方案
在 Laravellatest()
中,orderByDesc('created_at')
和orderBy('created_at', 'desc')
是等价的,它们会按descending
顺序获取数据。
latest()
默认列是created_at
,默认方向是descending
$thread = Thread::with(['messages' => function($q) {
$q->with('detail_per_user');
$q->with('post');
$q->with(['forum' => function($sq) {
$sq->with(['forum_messages' => function($isq) {
$isq->orderBy('id', 'ASC');
}]);
}]);
$q->with('attachments');
$q->latest('id');
$q->take(20);
}])->with('users.user_details:id,avtar,name,parent_id,generated_id')->where('id', '=', $thread_id)->get()->sortBy('id')->toArray();
首先我们messages
按顺序排序id
,descending
然后我们取 20 条记录,然后collection
按id
顺序ascending
排序。
您可能需要在->values()
之后添加,sortBy('id')
因为记录键将被重新排序。
推荐阅读
- javascript - Laravel 刀片中的 Unicode JSON 用于 React,生成 JSON.parse 问题
- apache-spark - “ilike”关键字不适用于 spark SQL
- swift - Swift 验证函数
- python-3.x - 如何将 4d alpha 通道转换为 3D rgb?
- python - Python中的“变量”赋值
- graphdb - 使用 REST API 或 RDF4J API 将数据加载到 GraphDB 中的命名图
- python - 我可以切换 PyTesseract 配置中间脚本吗?
- git - 如何在 Git 中恢复其他人的提交?
- mocking - 使用 OpenAPI 3.0 是否可以将布尔查询参数链接到特定示例
- python - 如何检查 DataFrame 列中是否存在元组值