2017-02-25 68 views
0

我有一个名为Tag的实体,它有3个ManyToMany关系fests,文章和新闻。Symfony3 querybuilder orderby count few manytomany

AppBundle\Entity\Tag: 
    type: entity 
    table: tag 
    ... 
    manyToMany: 
     news: 
      orderBy: { 'posted': 'DESC' } 
      targetEntity: News 
      inversedBy: tags 
      joinTable: 
      name: news_tag 
      joinColumns: 
       tag_id: 
       referencedColumnName: id 
      inverseJoinColumns: 
       news_id: 
       referencedColumnName: id 
     articles: 
      orderBy: { 'posted': 'DESC' } 
      targetEntity: Article 
      inversedBy: tags 
      joinTable: 
      name: article_tag 
      joinColumns: 
       tag_id: 
       referencedColumnName: id 
      inverseJoinColumns: 
       article_id: 
       referencedColumnName: id 
     fests: 
      orderBy: { 'when_starts': 'DESC', 'when_ends': 'DESC' } 
      targetEntity: Fest 
      inversedBy: tags 
      joinTable: 
      name: fest_tag 
      joinColumns: 
       tag_id: 
       referencedColumnName: id 
      inverseJoinColumns: 
       fest_id: 
       referencedColumnName: id 

现在我想写一个createQueryBuilder通过计数单“新闻” +计数“的文章” +计数“巨星汇”,只是为了找到“热门标签”。我只为一个manyToMany关系找到解决方案。

有没有办法做到这一点?

编辑: 我有什么:

$qb->select(array(
     't.id', 
     't.name', 
     'COUNT(f) as festcount', 
     'COUNT(n) as newscount', 
     'COUNT(a) as articlescount', 
     '(COUNT(f) + COUNT(n) + COUNT(a)) as totalcount' 
     )) 
    ->from('AppBundle:Tag', 't') 
    ->leftJoin('t.fests', 'f') 
    ->leftJoin('t.articles', 'a') 
    ->leftJoin('t.news', 'n') 
    ->groupBy('t.id') 
    ->orderBy('totalcount', 'DESC'); 

但它给人假的结果。当一些标签具有3个测试信息,1篇文章和新闻0,结果是festcount = 3,newscount = 0,articlescount = 3和TOTALCOUNT = 6,并且它应该是4.

+0

文章缺少您想要达到的代码。 –

+0

@michail_w感谢您的评论,我写道,我需要'构建'createQueryBuilder,它将选择通过所有关系(新闻+文章+ fests)DESC计数总和排序的标签。 – unbreak

+0

StackOverflow的规则是帮助人们解决他们的问题,而不是去做他们的工作。在您发布您已有的queryBuilder代码之前,没有人会回答这个问题。 –

回答

1

尝试此代码:

$qb->select(array(
     't.id', 
     't.name', 
     'COUNT(DISTINCT f.id) as festcount', 
     'COUNT(DISTINCT n.id) as newscount', 
     'COUNT(DISTINCT a.id) as articlescount', 
     '(festcount + newscount + articlescount) as totalcount' 
     )) 
    ->from('AppBundle:Tag', 't') 
    ->leftJoin('t.fests', 'f') 
    ->leftJoin('t.articles', 'a') 
    ->leftJoin('t.news', 'n') 
    ->groupBy('t.id') 
    ->orderBy('totalcount', 'DESC'); 

如果您需要进一步帮助,请提供这些表格的转储。

+0

哇!我不知道为什么,但它有效。 BTW。这行:'(festcount + newscount + articlescount)作为totalcount''我需要写为:(COUNT(DISTINCT f)+ COUNT(DISTINCT n)+ COUNT(DISTINCT a))作为totalcount'因为即时通讯错误' SQLSTATE [42S22]:未找到列:1054'字段列表'中的未知列'sclr_2' – unbreak