PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 15, 2022

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

 November 15, 2022     eloquent, laravel, laravel-6, php, sql-order-by     No comments   

Issue

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?


Solution

In this case you need to use orderByRaw for your custom expressions

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


Answered By - M Khalid Junaid
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing