I am using Zend Framework 3
and Doctrine2
in this project.
I have a nested entity which is build like a tree hierarchy.
[Project] 1 - n [WorkOrders] 1 - n [WorkOrderItems]
Every WorkOrderItem
has a status - to simplify for the example that status can be 1 for not finished or 2 for finished. I now want to display the progress of the project by iterating over all WorkOrderItems
and calculate the percent like so:
$finishedWorkOrderItems = 0;
$totalWorkOrderItems = 0;
foreach ($this->getWorkOrders() as $workOrder) {
foreach ($workOrder->getWorkOrderItems() as $workOrderItem) {
if ($workOrderItem->getStatus() == WorkOrderItem::STATUS_FINISHED) {
$finishedWorkOrderItems++;
}
$totalWorkOrderItems++;
}
}
return 100 / $totalWorkOrderItems * $finishedWorkOrderItems;
When displaying a list of 50 Projects the loadtime until the View is completely rendered is very high - between 7 and 9 seconds. When rendering the list without the progress the render time is significantly lower - between 0.5 and 2s.
I tried to use a custom DQL
for the project and join the needed data in the select statement like so :
$queryBuilder = $entityManager->createQueryBuilder();
$queryBuilder
->select(['p', 'o', 'oi'])
->from(Project::class, 'p')
->join('p.orders', 'o')
->join('o.orderItems', 'oi')
->groupBy('p');
Which gave me no measurable performance boost.
Why not get your total count directly from DQL instead of a nested loop
SELECT p,
COUNT(DISTINCT o.id) AS totalOrders,
COUNT(oi.id) AS totalOrdersItems,
SUM(CASE WHEN oi.status = 'some status' THEN 1 ELSE 0 END) AS totalWorkedOrdersItems
FROM Bundle\Entity\Project p
LEFT JOIN p.orders o
LEFT JOIN o.orderItems oi
GROUP BY p.id