2013-10-27 80 views
0

我有兩個實體「文章」和「類別」(爲博客)之間的一個簡單的關係ManyToMany。我想用特定類別獲取每篇文章,但我不知道如何創建該查詢。我做的是:與ManyToMany關係的主義查詢

$query = $em->createQuery(
     'SELECT u 
     FROM SiteBlogBundle:article u 
     WHERE u.categorie.name = :cat 
     ORDER BY u.date DESC' 
    ) 
     ->setParameter('cat', '$cateogory') 

WHERE u.categorie.name = :cat不起作用。我怎樣才能做到這一點?

回答

1

如果你還好用的查詢建設者可讀性更好,而不是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()) 
    ; 
} 
+0

這就是我需要的,謝謝! – user2108742