I'm trying to optimize this query, which has a subquery:
$subQuery = $em
->createQueryBuilder()
->select('o')->distinct()
->from('AppBundle:Report', 'o')
->groupBy('o.project')
->having('MIN(o.createdAt) between :start AND :end')
;
$query = $em
->createQueryBuilder()
->select('p')
->from ('AppBundle:Project', 'p')
->leftjoin('project.reports', 'r')
->andWhere(
$query->expr()->in('r', $subQuery->getDQL())
)
->setParameter('start', $filters['start-report-date'])
->setParameter('end', $filters['end-report-date'])
;
Although it works well, the subquery returns almost 100,000 records, and the process slows down a lot.
I've tried with:
$query = $em
->createQueryBuilder()
->select('p')
->from ('AppBundle:Project', 'p')
->leftjoin('project.reports', 'r')
->groupBy('p.id')
->having('MIN(o.createdAt) between :start AND :end')
->setParameter('start', $filters['start-report-date'])
->setParameter('end', $filters['end-report-date'])
;
But when executing doctrine returns error:
No result was found for a query although at least one row was expected.
Reviewing the log generated by the symfony, I see that "no result was found" is due to a previous query, which adds a count () at the beginning:
DEBUG - SELECT DISTINCT p0_.id AS id_0,
p0_.created_at AS created_at_1
FROM project p0_
LEFT JOIN rfq r1_ ON p0_.rfq_id = r1_.id
LEFT JOIN place p2_ ON p0_.place_id = p2_.id
LEFT JOIN customer c3_ ON p0_.customer_id = c3_.id
LEFT JOIN report r4_ ON p0_.id = r4_.project_id
WHERE p0_.deleted_at IS NULL
AND p0_.type IN ('tracking_project')
AND p0_.type IN ('tracking_project')
HAVING MIN(r4_.created_at) BETWEEN ? AND ?
ORDER BY p0_.created_at DESC
LIMIT 10 OFFSET 0
DEBUG - SELECT count(DISTINCT p0_.id) AS sclr_0
FROM project p0_
LEFT JOIN rfq r1_ ON p0_.rfq_id = r1_.id
LEFT JOIN place p2_ ON p0_.place_id = p2_.id
LEFT JOIN customer c3_ ON p0_.customer_id = c3_.id
LEFT JOIN report r4_ ON p0_.id = r4_.project_id
WHERE p0_.deleted_at IS NULL
AND p0_.type IN ('tracking_project')
AND p0_.type IN ('tracking_project')
HAVING MIN(r4_.created_at) BETWEEN ? AND ?
CRITICAL - Uncaught PHP Exception Doctrine\ORM\NoResultException: "No result was found for query although at least one row was expected." at /home/angel/desarrollo/gpar/vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/SingleScalarHydrator.php line 43
I think I have the flaw in the form of having and groupBy, but I do not see how to solve it ...: (