Symfony:将 SQL 查询转换为正确的 Doctrine QueryBuilder 实例

Symfony: Turning a SQL query into a correct Doctrine QueryBuilder Instance

我需要在 symfony 中为以下 SQL:

提供一个有效的查询构建器
SELECT
(SELECT COUNT(ii.invoice_id) FROM invoice WHERE invoice_number = i.invoice_number) as c, 
i.id as invoice_id, i.invoice_number, ii.logistician_id FROM invoice i
LEFT JOIN incoming_invoice ii ON i.id = ii.invoice_id
GROUP BY invoice_id
HAVING c < 2;

我从昨天开始测试,但我没有让它工作。

public function findAllWithoutIncomingInvoice(): array
{
    return $this->createQueryBuilder('i')
        ->select('i, ii, COUNT(ii.invoice_id) FROM invoice WHERE invoice_number = i.invoice_number) as c')
        ->leftJoin('i.incomingInvoices', 'ii')
        ->groupBy('i.id')
        ->having('c < 2')
        ->setMaxResults(15)
        ->getQuery()
        ->getResult();
}

错误:

[Semantical Error] line 0, col 40 near 'invoice WHERE': Error: Class 'invoice' is not defined.

你应该正确命名你的别名,这样更容易阅读你的代码。
另外,确保你使用双引号来编写你的 DQL,因为 Doctrine 将需要围绕文本值的简单引号

至于你的答案,应该是这样的:

public function findAllWithoutIncomingInvoice(): array {
    $qb = $this->_em->createQueryBuilder();

    $qb->select("invoice")
       ->from(Invoice::class, "invoice")
       ->join("invoice.incomingInvoice", "incomingInvoice")
       ->groupBy("invoice.id")
       ->having("COUNT(incomingInvoice.id) < 2");

    return $qb->getQuery()->getResult();
}