fixed N+1 issues
This commit is contained in:
@@ -22,7 +22,8 @@ final class WorkflowNotificationService
|
||||
*/
|
||||
public function dispatch(Ticket $ticket, string $event, ?User $actor = null): void
|
||||
{
|
||||
$ticket->loadMissing(['user.company', 'owner.company', 'agent.company', 'status', 'priority', 'category', 'project', 'team', 'product']);
|
||||
$this->hydrateTicketUsers($ticket);
|
||||
$ticket->loadMissing(['status', 'priority', 'category', 'project', 'team', 'product']);
|
||||
$actor?->loadMissing('company');
|
||||
|
||||
WorkflowTemplate::query()
|
||||
@@ -64,6 +65,43 @@ final class WorkflowNotificationService
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Load requester/agent with one query if the caller has not already attached them.
|
||||
*/
|
||||
private function hydrateTicketUsers(Ticket $ticket): void
|
||||
{
|
||||
if ($ticket->relationLoaded('owner') && $ticket->relationLoaded('agent')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$userIds = collect([$ticket->user_id, $ticket->agent_id])
|
||||
->filter()
|
||||
->map(static fn (mixed $id): int => (int) $id)
|
||||
->unique()
|
||||
->values();
|
||||
|
||||
if ($userIds->isEmpty()) {
|
||||
$ticket->setRelation('user', null);
|
||||
$ticket->setRelation('owner', null);
|
||||
$ticket->setRelation('agent', null);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$users = User::query()
|
||||
->with('company')
|
||||
->whereIn('id', $userIds)
|
||||
->get()
|
||||
->keyBy('id');
|
||||
|
||||
$owner = $users->get((int) $ticket->user_id);
|
||||
$agent = $ticket->agent_id === null ? null : $users->get((int) $ticket->agent_id);
|
||||
|
||||
$ticket->setRelation('user', $owner);
|
||||
$ticket->setRelation('owner', $owner);
|
||||
$ticket->setRelation('agent', $agent);
|
||||
}
|
||||
|
||||
private function recipient(string $role, Ticket $ticket, ?User $actor): ?User
|
||||
{
|
||||
return match ($role) {
|
||||
|
||||
Reference in New Issue
Block a user