Skip to content

Commit

Permalink
Reduce queries for counting notifications
Browse files Browse the repository at this point in the history
  • Loading branch information
nanaya committed Oct 29, 2024
1 parent 87bf4e5 commit c06219a
Showing 1 changed file with 21 additions and 9 deletions.
30 changes: 21 additions & 9 deletions app/Libraries/NotificationsBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ private static function stackKey(string $objectType, int $objectId, string $cate
}

private $category;
private array $countByType;
private $cursorId;
private $objectId;
private $objectType;
Expand Down Expand Up @@ -61,7 +62,7 @@ public function toArray()
];

if ($this->unreadOnly) {
$response['unread_count'] = $this->user->userNotifications()->hasPushDelivery()->where('is_read', false)->count();
$response['unread_count'] = $this->getTotalNotificationCount();
}

return $response;
Expand Down Expand Up @@ -186,18 +187,29 @@ private function fillTypes(?string $type = null)

private function getTotalNotificationCount(?string $type = null)
{
$query = Notification::whereHas('userNotifications', function ($q) {
$q->hasPushDelivery()->where('user_id', $this->user->getKey());
if ($this->unreadOnly) {
$q->where('is_read', false);
if (!isset($this->countByType)) {
$query = Notification ::whereHas('userNotifications', function ($q) {
$q->hasPushDelivery()->where('user_id', $this->user->getKey());
if ($this->unreadOnly) {
$q->where('is_read', false);
}
});

if ($this->objectType !== null) {
$query->where('notifiable_type', $this->objectType);
}
});

if ($type !== null) {
$query->where('notifiable_type', $type);
$this->countByType = $query
->groupBy('notifiable_type')
->selectRaw('count(*) type_count, notifiable_type')
->get()
->mapWithKeys(fn ($agg) => [$agg->notifiable_type => $agg->type_count])
->all();
}

return $query->count();
return $type === null
? array_sum($this->countByType)
: $this->countByType[$type] ?? 0;
}

private function getStackHeads(?string $type = null)
Expand Down

0 comments on commit c06219a

Please sign in to comment.