A curated list of useful Doctrine snippets.
Contributions are highly encouraged and very welcome :)
$em = $this->getEntityManager();
$query = $em->createQuery('SELECT c FROM SomeBundle:Configuration c INDEX BY c.name');
$query->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
SELECT partial b{id, title} FROM Book b
$qb = $em->createQueryBuilder();
$qb->select('u')
->from('SomeUserBundle:User', 'u', 'u.id')
->add('where', $qb->expr()->like('u.roles', ':role'))
->setParameter('role', $role);
$query->getOneOrNullResult();
- no result: return
null
- more than one result: throw an
NonUniqueResultException
exception
SELECT m, (m.comments + m.likes_count) AS HIDDEN score FROM Midia m ORDER BY score
$query = $entityManager->createQuery('SELECT COUNT(u.id) FROM User u');
$count = $query->getSingleScalarResult();
Doctrine 2.4
$categories = ...
$categoryIds = array();
foreach ($categories as $category) {
$categoryIds[] = $category->getId();
}
$queryBuilder = $this
->where('model.category IN (:category_ids)')
->setParameter('category_ids', $categoryIds);
Doctrine 2.5+ supports ArrayCollection
$queryBuilder = $this
->where('model.category IN (:categories)')
->setParameter('categories', $categories);
If you have a very large UnitOfWork but know that a large set of entities has not changed, just mark them as read only.
$entityManager->getUnitOfWork()->markReadOnly($entity)
$entityManager->flush($entity)