首页 > 解决方案 > 使用 Doctrine Query Builder 转换 SQL 查询

问题描述

SQL - 是正确的并且在 mysql-console 中工作。我有一些 SQL 查询,用于从数据库产品中进行选择。我试图将它放入存储库,但它根本不起作用。

这里还有 ProductRepository 的功能代码

有人可以帮助我或显示我的错误并解释如何将 SQL 转换为查询构建器查询或强制使用纯 SQL 吗?

SELECT *
FROM accounting_products
LEFT JOIN accounting_incoming_invoice_items 
    ON accounting_incoming_invoice_items.product_id = accounting_products.id
WHERE accounting_incoming_invoice_items.outcome_price >
          accounting_incoming_invoice_items.price;
    public function findAllOnStorage()
    {
        $rsm = new ResultSetMapping($this->getEntityManager());

        $query = $this->getEntityManager()->createNativeQuery(
            "SELECT * FROM accounting_products LEFT JOIN accounting_incoming_invoice_items 
                    ON accounting_incoming_invoice_items.product_id = accounting_products.id
                    WHERE accounting_incoming_invoice_items.outcome_price > accounting_incoming_invoice_items.price;",
            $rsm);

        $all = $query->getResult();
        #dump($all);exit;
        return $all;
    }

如果在存储库中纯 SQL - 它只是不起作用。查询的结果是空集,但在控制台中,它只返回一条记录

尝试将 SQL 转换为查询构建器没有任何成功。

标签: phpsqlsymfonydoctrineleft-join

解决方案


$qrBuilder = $this->createQueryBuilder('p')
    ->select('p', 'i')
    ->leftJoin(IncomingInvoiceItem::class, 'i')
    ->where('i.outcomePrice > i.price');


$all = $qrBuilder->getQuery()->getResult();

但是 MariaDB 仍然抛出错误:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE a1_.outcome_price > a1_.price' at line 1

推荐阅读