首页 > 解决方案 > 如何在 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 顺序排列。

标签: phpmysqllaravel

解决方案


在 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按顺序排序iddescending然后我们取 20 条记录,然后collectionid顺序ascending排序。

您可能需要在->values()之后添加,sortBy('id')因为记录键将被重新排序。


推荐阅读