我有ArticleToOne关系的Article和Category Entity。我想列出其中包含文章数量的类别。如何使用Doctrine2 高效查询它?
答案 0 :(得分:1)
如果您已正确设置类别实体,那么您可以通过调用其getter计数来获取其文章集合,假设您的实体映射如下
第
class Article
{
// ...
/**
* @ORM\ManyToOne(targetEntity="Category", inversedBy="articles")
* @ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category;
// ... title ,id ,bla bla bla
}
分类
use Doctrine\Common\Collections\ArrayCollection;
class Category
{
// ...
/**
* @ORM\OneToMany(targetEntity="Article", mappedBy="category")
*/
protected $articles;
// ... title ,id ,bla bla bla
public function __construct()
{
$this->articles= new ArrayCollection();
}
}
然后你可以在控制器中循环你的类别实体
$DM = $this->getContainer()->getDoctrine()->getManager();
$categories = $DM->getRepository('Namespace\YourBundle\Entity\Category')->findAll();
foreach($categories as $c){
echo $this->getTitle();
echo count($this->getArticles());
}
在树枝上
{% for c in categories %}
{{ c.getTitle() }}
{{ c.getArticles()|length }}
{% endfor %}
通过查询构建器,您可以这样做
$DM = $this->getContainer()->getDoctrine()->getManager();
$query = $DM->createQueryBuilder()
->select('c.id,c.title, COUNT(a.id) as article_count')
->from('NamespaceYourBunle:Category', 'c')
->innerJoin('c.articles', 'a')
->groupBy('c.id')
;
$categories= $query->getQuery()->getResult();