Orderby Desc在雄辩的Laravel中

时间:2018-10-25 07:53:33

标签: laravel orm eloquent laravel-5.6

我有一个查询,将3个表连接在一起,我想按从消息表中created_at降序排列的结果,请帮忙。谢谢。

控制器:

 return new AllChats(Chat::latest('created_at')->whereHas('messages')->with(['messages.users', 'users' =>
        function ($query) {
            $query->where('id', '!=', Auth::id());
        }])->whereHas('users', function ($query) {
            $query->where('id', '=', Auth::id());
        })->get());

以desc顺序显示结果,但来自messages.created_at ??

3 个答案:

答案 0 :(得分:0)

这样使用

return new AllChats(Chat::latest('created_at')>>whereHas('messages',function($q){
    $q->orderBy('created_at', 'desc');
 })->with(['messages.users', 'users' =>
    function ($query) {
        $query->where('id', '!=', Auth::id());
    }])->whereHas('users', function ($query) {
        $query->where('id', '=', Auth::id());
    })->get());

答案 1 :(得分:0)

您只需在查询的 创建于 字段上添加-> orderBy

return new AllChats(Chat::latest('created_at')->whereHas('messages')->with(['messages.users', 
    'users' => function ($query) {
        $query->where('id', '!=', Auth::id());
    }])
    ->orderBy('created_at', 'desc')
    ->whereHas('users', function ($query) {
        $query->where('id', '=', Auth::id());
    })->get());

Sample Example

参考:https://laravel.com/docs/5.7/eloquent

答案 2 :(得分:0)

您可以使用修改后的withCount()

$chats = Chat::withCount(['messages as latest_message' => function($query) {
        $query->select(DB::raw('max(created_at)'));
    }])
    ->orderByDesc('latest_message')
    [...]
    ->get();