i have a query to fetch all data and these data are support tickets, each support ticket has many comments, i want to order these data by last comment if exists else order by ticket created date
any idea what is the issue here and how i can fix it?
thanks in advance
$builder->select('support_tickets.*', DB::raw('(SELECT max(created_at) as latest_created_at FROM ticket_activities WHERE support_tickets.id = ticket_activities.ticket_id GROUP BY ticket_id) as latest'))
->orderByRaw('CASE WHEN EXISTS (SELECT max(created_at) as latest_created_at FROM ticket_activities WHERE support_tickets.id = ticket_activities.ticket_id GROUP BY ticket_id) THEN support_tickets.created_at ELSE latest END DESC')
->paginate(Arr::get($setting, 'perPage', 40));
it is return Invalid column name ‘latest’
2
Answers
I think joining this tables make things simpler:
SQL Server COALESCE() Function Return the first non-null value in a list.