使用LeftJoin的DQL请求

时间:2017-06-15 08:30:34

标签: symfony doctrine-orm dql

我想计算在我的博客中使用主题的次数。

任何博文(法语文章)都可以使用一个或多个主题。

所以我有一张桌子(ManyToMany):

  • themes_articles(id_theme,id_article)和:
  • 主题(id_theme,nom_theme)
  • 文章(博文)(id_article,description ...)

在SQL中,我这样做:

SELECT T.id,nom_theme,count(A.themes_id) from themes_articles A right join themes T on T.id=A.themes_id group by nom_theme

它有效,但是当我想在DQL中使用正确的连接时,它有点难。我切换了我的两个表以使用左连接,但我不知道如何在这里使用我的关系表(themes_articles)。

我试过这样的事情:

 $query = $this->createQueryBuilder('')
->select(array('T.id', 'nomTheme', 'count(A.themes_id) as nombre'))
->from('themes', 'T')
->leftJoin('themes_articles', 'A', 'WITH', 'T.id= A.themes_id')
->groupBy('nom_theme');
    return $query->getQuery()->getResult();

但它不起作用。

[Semantical Error] line 0, col 93 near 'themes_articles': Error: Class 'themes_articles' is not defined.

如何在DQL请求中转换我的SQL请求?

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

像这样使用

$query = $this->createQueryBuilder()
   ->select(array('t.id', 't.nomTheme', 'count(ta.themes_id) as nombre'))
   ->from('<YOUR BUNDLE>:<Theam Entity Class>', 't') //Like AcmeTheamBundle:Themes
   ->leftJoin('t.themes_articles') 
   ->groupBy('t.nomTheme'); //better to use theam id
   return $query->getQuery()->getResult();

答案 1 :(得分:0)

它好一点!我必须在我的请求中添加文章和主题(contient)之间关系的名称。

  $query = $this->createQueryBuilder('t')
   ->select(array('t.id', 't.nomTheme', 'count(ta.id) as nombre'))
   ->leftJoin('t.contient', 'ta', 'WITH', 't.id= ta.id') 
   ->groupBy('t.nomTheme'); //better to use theam id
   return $query->getQuery()->getResult();
相关问题