如何将SQL查询转换为Doctrine2?

时间:2015-03-13 15:57:06

标签: php sql symfony doctrine-orm dql

我想在Doctrine2中转换它。

与这些问题类似:
Symfony2 / Doctrine2 - How to convert this SQL request with QueryBuilder?
How to convert a complex MySQL Query to Doctrine2
Convert SQL to Doctrine 2 Query Builder or DQL by using NOT IN?

有可能吗?

SELECT 
SUM(q.amount)

FROM(
 SELECT  amount
    FROM expense_report e0_
    WHERE
        (e0_.is_account_transfer = 0)
            AND (e0_.remove_date IS NULL)
    LIMIT 0, 2) q

由于

1 个答案:

答案 0 :(得分:0)

您可以使用此自定义存储库方法存档问题:

public function getAmount()
{
    $qb = $this->createQueryBuilder("q");
    return
        $qb
            ->select("sum(q.amount)")
            ->where($qb->expr()->isNull('q.remove_date'))
            ->andWhere('q.is_account_transfer = 0')
            ->setFirstResult(0)
            ->setMaxResults(2)
            ->getQuery()
            ->getSingleScalarResult();
}

只需在控制器方法中使用它,例如:

public function testAction()
{
   ....
    $totalAmount = $this->getDoctrine()
                        ->getRepository("AcmeDemoBundle:ExpenseReport")
                        ->getAmount();
    ...
}

希望这个帮助