如何在 laravel 中对多个 withcount() 列进行求和和排序

How to multiple withcount() columns sum and order by in laravel

我需要根据 laravel 6

中的 withcount() 函数按记录排序
 $query=User::withCount(['time_spent' =>function($q){
                        $q->select(\DB::raw('COALESCE(sum(COALESCE(time_spent, 0 )),0)'))
                        ->whereDate("created_at", ">=", Carbon::today()->startOfMonth()->toDateString())
                        ->whereDate("created_at", "<=", Carbon::today()->endOfMonth()->toDateString());
                    }])
                    ->withCount(['interactive_time_spent' =>function($q){
                        $q->select(\DB::raw('COALESCE(sum(COALESCE(audio_video_time, 0 ) + COALESCE(chat_time,0)),0)'))
                        ->whereDate("created_at", ">=", Carbon::today()->startOfMonth()->toDateString())
                        ->whereDate("created_at", "<=", Carbon::today()->endOfMonth()->toDateString());
                    }])
                    ->orderBy("(interactive_time_spent_count + time_spent_count)",$sortOder)->get();

在此代码中,我有两个 withCount() 函数,我需要根据 get() 之前的两列总和对 By 进行排序。 它在使用一列排序时有效,但如果我使用两列,那么它 returns 一个未知列。可不可以?

在这种情况下,您需要使用 orderByRaw 作为您的自定义表达式

->orderByRaw("(interactive_time_spent_count + time_spent_count) ".$sortOder)