I have a quite complex SQL query to get delay average between ticket creation and first message of the support team:
SELECT u.username,
AVG(((
SELECT UNIX_TIMESTAMP(tm.added_at)
FROM ticket_message tm
INNER JOIN `fos_user` tmu ON tm.author_id = tmu.id
LEFT JOIN `fos_user_user_group` tmug ON tmu.id = tmug.user_id
LEFT JOIN `fos_group` tmg on tmug.group_id = tmg.id
WHERE tm.ticket_id = t.id
AND (tmu.roles LIKE '%ROLE_SUPPORT%' OR tmg.roles LIKE '%ROLE_SUPPORT%')
ORDER BY tm.added_at LIMIT 1
) - UNIX_TIMESTAMP(t.added_at))) / 60 as delay
FROM `fos_user` u
INNER JOIN `ticket` t on u.id = t.assigned_id
GROUP BY u.id
This query works like that. I want to do the same with DQL. I tried:
$averageQb = $this->prepareUserTopQB();
$averageQb
->innerJoin('u.assignedTickets', 't', Join::WITH, 't.addedAt BETWEEN :begin AND DATE_ADD(:end, 1, \'DAY\')')
->addSelect('AVG(('.$messageQb->getDQL().') - UNIX_TIMESTAMP(t.addedAt)) / 60 as average')
->orderBy('average')
;
And with Expr:
$averageQb = $this->prepareUserTopQB();
$averageQb
->innerJoin('u.assignedTickets', 't', Join::WITH, 't.addedAt BETWEEN :begin AND DATE_ADD(:end, 1, \'DAY\')')
->addSelect(
$averageQb->expr()->quot(
$averageQb->expr()->avg($averageQb->expr()->diff(
$messageQb->getDQL(),
'UNIX_TIMESTAMP(t.addedAt)'
)),
60
).' as average'
)
->orderBy('average')
;
But I have this error with both methods:
[1/2] QueryException: SELECT u.id user_id, u.username, u.firstname, u.lastname, u.email, AVG(SELECT tm.addedAt FROM AppBundle:TicketMessage tm INNER JOIN tm.author tma LEFT JOIN tma.groups tmg WHERE tm.id = t.id AND (tma.roles LIKE '%ROLE_SUPPORT%' OR tmg.roles LIKE '%ROLE_SUPPORT%') ORDER BY tm.addedAt ASC - UNIX_TIMESTAMP(t.addedAt)) / 60 as average FROM AppBundle\Entity\User u INNER JOIN u.groups g WITH g.name = 'Support' INNER JOIN u.assignedTickets t WITH t.addedAt BETWEEN :begin AND DATE_ADD(:end, 1, 'DAY') GROUP BY u ORDER BY average ASC
[2/2] QueryException: [Syntax Error] line 0, col 71: Error: Expected Literal, got 'SELECT'
I have to use DQL but Doctrine seems to not like to have a select inside an average function.
How to solve this issue?
Thanks