Skip to content

Instantly share code, notes, and snippets.

@ishukshin
Forked from peterjmit/dont-do-this.php
Last active September 18, 2015 10:44
Show Gist options
  • Save ishukshin/81d451e7549e90bb4343 to your computer and use it in GitHub Desktop.
Save ishukshin/81d451e7549e90bb4343 to your computer and use it in GitHub Desktop.
Some Doctrine 2 Best Practices got here - http://www.uvd.co.uk/blog/some-doctrine-2-best-practices/
<?php
$articles = $article_repository->findAll();
foreach($articles as $article)
{
echo $article->getTitle();
echo count($article->getComments());
}
<?php
//$em is the entity manager
$qb = $em->createQueryBuilder();
$qb
->select('Article', 'Comment')
->from('Entity\Article', 'Article')
->leftJoin('Article.comment', 'Comment')
;
$query = $qb->getQuery();
return $query->getResult();
<?php
//$em is the entity manager
$qb = $em->createQueryBuilder();
// Wasteful, will select all the properties (columns) for the entity
$qb
->select('Article')
->from('Entity\Article')
;
// Better, but won't provide a structure representing our object graph (returns a flat array)
$qb
->select('Article.title')
->from('Entity\Article')
;
// Best (although fragile if trying to manipulate/persist objects later)
$qb
->select('partial Article.{title}')
->from('Entity\Article')
;
// You can select multiple properties in the partial statement
$qb
->select('partial Article.{id,title,summary}')
->from('Entity\Article')
;
<?php
$qb = $em->createQueryBuilder();
$qb
->select('Article', 'Comment')
->from('Entity\Article', 'Article')
->leftJoin('Article.comment', 'Comment')
->where($qb->expr()->eq('Article.title', ':filter_title')
->setParameter('filter_title', $some_user_input)
;
$query = $qb->getQuery();
return $query->getResult();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment