Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

laravel order by before group by

//query below will fetch the latest entry saved in users table with a company
//in this case, there are a lot of users associated to company id = 1
//and we need to fetch only the latest user saved for this company
$latest_added_user = DB::table('company')
                ->select('company.*', 'users.*')
                ->leftJoin('users', function($query) {
                   $query->on('company.id','=','users.company_id')
                   ->whereRaw('users.id IN (select MAX(a2.id) from users as a2 join company as u2 on u2.id = a2.company_id group by u2.id)');
                })
                ->whereIn('company.id', 1)
                ->get();
 
PREVIOUS NEXT
Tagged: #laravel #order #group
ADD COMMENT
Topic
Name
4+1 =