Kevin Bond
Kevin Bond

Reputation: 722

Doctrine2 empty collection creates unnecessary query

I have an Doctrine2 entity with an images collection. Here is my query:

$qb = $this->createQueryBuilder('page');
    $qb->select('page, image');
    $qb->where('page.id = ?1')
       ->leftJoin('page.images', 'image')
       ->setParameter(1, $id);

$result = $qb->getQuery()->getOneOrNullResult();

When I call $result->getImages() and the images collection is empty there is an extra call to the database. How can I prevent this?

Upvotes: 1

Views: 245

Answers (1)

Jerem
Jerem

Reputation: 470

I had the same problem with native query and I solved it by marking the freshly mapped collection as initialized .

if($result->getImages() instanceof PersistentCollection)
    $result->getImages()->setInitialized(true);
}

Doctrine don't call anymore the DB to check if there is children. Huge optimisation !

Upvotes: 3

Related Questions