将SQL查询转换为Doctrine 2

时间:2012-06-14 21:15:52

标签: sql symfony doctrine-orm

我有两张桌子:

author (id, first_name, last_name)
books (id, title, rate, author_id)

我需要获得评分最高的作者(每位作者一本)。

在sql中:

SELECT a.*, highest_rated_book.*
      FROM authors a
      LEFT JOIN (SELECT * FROM books b ORDER BY b.rate DESC) AS highest_rated_book
      ON a.id = highest_rated_book.author_id
      GROUP BY highest_rated_book.author_id
      ORDER BY a.id;

但是我需要在Doctrine 2中使用它。我遇到的最大问题是组合左连接和子选择。

这可能吗?

1 个答案:

答案 0 :(得分:1)

使用DQL,您似乎只能加入关联的实体(参见http://docs.doctrine-project.org/projects/doctrine-orm/en/2.0.x/reference/dql-doctrine-query-language.html#from-join-and-index-by)。

您可以使用本机查询,它允许您使用原始SQL。

可以在此处找到有关使用Doctrine 2的Native SQL的更多信息:http://docs.doctrine-project.org/en/latest/reference/native-sql.html