Hey All,
How can i optimize my below DB query and i also want paginated data.
$notifications = \App\Models\Notification::query()
->select(
'notifications.*',
\DB::raw('COUNT(*) as notifications_count'),
\DB::raw('MAX(created_at) as max_created_at'),
\DB::raw('(
SELECT GROUP_CONCAT(
CONCAT(
u.echo_user_id,
":", u.first_name, " ", u.last_name,
":", u.profile_pic,
":", n.id
)
ORDER BY n.created_at DESC SEPARATOR "|"
)
FROM echo_users u
INNER JOIN notifications n ON n.from_userid = u.echo_user_id
WHERE FIND_IN_SET(n.id, SUBSTRING_INDEX(GROUP_CONCAT(notifications.id ORDER BY notifications.created_at DESC), ",", 2)) > 0
ORDER BY n.created_at DESC
LIMIT 2
) AS latest_users')
)
->where('to_userid', request('user_id', 557))
->groupBy(['notifications.to_userid', 'notifications.post_id', 'notifications.type', 'notifications.comment_id'])
->orderByRaw('max_created_at DESC') // Order by latest notification
->paginate(15);
$notifications = $notifications->each(function ($notification) {
$notification->users = collect(explode('|', $notification->latest_users ?? ''))->map(function ($userDetails) {
[$echo_user_id, $full_name, $profile_pic] = explode(':', $userDetails);
return (object) compact('echo_user_id', 'full_name', 'profile_pic');
});
$user = $notification->users->pluck('full_name');
// Set the message based on the count
if ($notification->notifications_count === 1) {
$message = "{$user[0]} like your post.";
} elseif ($notification->notifications_count === 2) {
$message = "{$user[0]} and {$user[1]} likes your post.";
} else {
$totalNotifications = $notification->notifications_count - 1;
$message = "{$user[0]} and {$totalNotifications} others likes your post.";
}
$notification->message = $message;
});
Output: User A and 46 others likes your post.