如果您可以使用查询构建器而不是 DQL 来获得更好的可读性:
$articles = $em
->getRepository('SiteBlogBundle:Article')
->createQueryBuilder('article')
->leftJoin('article.category', 'category')
->where('category.name = :category_name')
->orderBy('article.date', 'DESC')
->setParameter('category_name', $category->getName())
->getQuery()
->getResult()
;
但我强烈建议您将此查询放入存储库中,如下所示:
// ArticleRepository.php
public function findArticlesByCategoryName($name)
{
return $this->createQueryBuilder('article')
->leftJoin('article.category', 'category')
->where('category.name = :category_name')
->orderBy('article.date', 'DESC')
->setParameter('category_name', $name)
->getQuery()
->getResult()
;
}
然后在你的控制器里面做:
public function getArticles(Category $category)
{
$em = $this->getDoctrine()->getEntityManager();
return $em->
getRepository('SiteBlogBundle:Article')
->findArticlesByCategoryName($category->getName())
;
}