Created
March 12, 2012 14:38
-
-
Save peterjmit/2022365 to your computer and use it in GitHub Desktop.
Some Doctrine 2 Best Practices
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$articles = $article_repository->findAll(); | |
foreach($articles as $article) | |
{ | |
echo $article->getTitle(); | |
echo count($article->getComments()); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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') | |
; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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