dsfdfd1211 2015-04-07 22:00
浏览 74
已采纳

使用Symfony Doctrine查询2个表的平均值

First of all, excuse me if my english isn't too good.

I'm using Symfony 2.6 with Doctrine as ORM. The project is running on Apache + MySQL.

I have 2 entities in my DB: book and rating. I'm building a system where the user can rate books from 0 to 100.

My entities:

  • Book: id, other unrelated fields
  • Rating: id, book_id, score, other unrelated fields

Every book can have many ratings but a rating can only be related to a single book (one to many mapping).

My goal is to get the top 5 books ordered by the average score of their ratings.

Example:

  • Book 1: 94.5
  • Book 2: 93.3
  • Book 3: 89.2
  • Book 4: 85.2
  • Book 5: 79.6

I already tried to get the result using a double for loop with the two entities, but according to the Symfony profiler, it took 3.7 seconds and required 1001 queries, wich is higly inefficient. I'm very sure it could be done in a better way using the DQL, so...

¿Which may be the most efficient way to achieve my goal (if possible in a single query)?

Thanks in advance.

EDIT

Thanks to MikO for the push in the right direction. Is required to write the complete entity (like AcmeBundle:Book) in the FROM and JOIN sentences for it to work. Also, you can't use LIMIT in a querybuilder, so after the query is built and before calling results, I had to use setMaxResults(5) in order to retrieve only the top 5 books.

Thanks very much.

  • 写回答

1条回答 默认 最新

  • douhui0975 2015-04-07 23:16
    关注

    I haven't actually tried this, but I'd create a custom repository class for your Book entity, and then I'd write something like this in it:

    public function getTopRatedBooks()
    {
        $em = $this->getEntityManager();
    
        $query = $em->createQuery('
          SELECT book.id, book.name, AVG(rating.score) as avg_rating
          FROM book 
          JOIN rating
          WHERE book.id = rating.book_id
          GROUP BY book.id
          ORDER BY avg_rating DESC
        ');
    
        $result = $query->getResult();
    
        return $result;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 经gamit解算的cors站数据再经globk网平差得到的坐标做形变分析
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式