symfony2 doctrine连接实体的计数

时间:2014-08-26 16:50:56

标签: php mysql sql symfony doctrine-orm

我有ArticleToOne关系的Article和Category Entity。我想列出其中包含文章数量的类别。如何使用Doctrine2 高效查询它?

1 个答案:

答案 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();