I have to need to order by records based on withcount() function in laravel 6
$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();
In this code, I have two withCount() functions and I need to order By based on that two-column sum before get().
It works when order by using one column but if I use two-column then it returns an unknown column. Is it possible or not?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
In this case you need to use orderByRaw
for your custom expressions
->orderByRaw("(interactive_time_spent_count + time_spent_count) ".$sortOder)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0