在连接表上使用条件的Doctrine DQL计数

时间:2013-10-02 09:59:32

标签: doctrine-orm

我有以下实体:

class Restaurant
{
    // ...
}

class Order
{
    /**
     * The Restaurant this order belongs to.
     *
     * @var Restaurant
     */
    protected $restaurant;

    /**
     * The status of this order: 'pending', 'accepted' or 'rejected'.
     *
     * @var string
     */
    protected $status;

    // ...
}

餐厅可以有零个或多个订单。

我想查询所有餐厅以及订单总数,以及每种状态下的订单数量。

我提出了以下问题:

SELECT r, COUNT(o.id) AS totalOrders
FROM Restaurant r
LEFT JOIN Order o WITH o.restaurant = r
GROUP BY r.id

如何计算pendingOrdersacceptedOrdersrejectedOrders的数量?

1 个答案:

答案 0 :(得分:3)

找到解决方案:

SELECT r, COUNT(o.id) AS totalOrders,
  SUM(CASE WHEN o.status = 'pending' THEN 1 ELSE 0 END) AS pendingOrders,
  SUM(CASE WHEN o.status = 'accepted' THEN 1 ELSE 0 END) AS acceptedOrders,
  SUM(CASE WHEN o.status = 'rejected' THEN 1 ELSE 0 END) AS rejectedOrders
FROM Restaurant r
LEFT JOIN Order o WITH o.restaurant = r
GROUP BY r.id