Skip to content

NikDevPHP/awesome-doctrine

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 

Repository files navigation

Awesome Doctrine

A curated list of useful Doctrine snippets.

Contributions are highly encouraged and very welcome :)

Table of Contents

DQL

Defining a Column to be the Key of the Result Hydrated as Array

$em = $this->getEntityManager();

$query = $em->createQuery('SELECT c FROM SomeBundle:Configuration c INDEX BY c.name');
$query->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);

[1]

Fetch Only Parts of an Entity

SELECT partial b{id, title} FROM Book b

INDEX BY in QueryBuilder

$qb = $em->createQueryBuilder();

$qb->select('u')
   ->from('SomeUserBundle:User', 'u', 'u.id')
   ->add('where', $qb->expr()->like('u.roles', ':role'))
   ->setParameter('role', $role);

Get Single Row or Null

$query->getOneOrNullResult();
  • no result: return null
  • more than one result: throw an NonUniqueResultException exception

[1] [2]

Ordering with Expressions

SELECT m, (m.comments + m.likes_count) AS HIDDEN score FROM Midia m ORDER BY score

Return Only a Value

$query = $entityManager->createQuery('SELECT COUNT(u.id) FROM User u');
$count = $query->getSingleScalarResult();

WHERE IN Clause

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);

Performance

Temporarily Mark Entities as Read-Only at Runtime

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)

[1]

About

A collection of useful Doctrine snippets.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published