我有一个名为Tag的实体,它有3个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,按计数“新闻”排序+计数“文章”+计数“fests”,仅用于查找“TOP TAGS”。我找到的解决方案只适用于一个很多关系。
有没有办法做到这一点?
编辑: 我有什么:
$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 :(得分: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');
如果您需要进一步的帮助,请提供这些表的转储。