doctrine的createQuery中的子查询

时间:2015-02-13 13:23:16

标签: php mysql symfony doctrine-orm

我正面临一个小问题,我希望有人可以帮助我。 在SQL中我有这个查询,它给了我想要的结果:

SELECT * FROM price_material AS y 
JOIN (
   SELECT * FROM price_material_price GROUP BY id DESC
) AS x 
GROUP BY y.price_material_id

现在我尝试将其转换为我的PHP项目:

    public function getPriceLines($pricelist = 0, $year = 0, $week = 0)
    {
        if ($year === 0) {
            $year = (int)date('Y');
        }

        if ($week === 0) {
            $week = (int)date('W');
        }

        $query = $this->getEntityManager()->createQuery('
          SELECT pgp FROM ACME\Bundle\PricelistBundle\Entity\PricelistMaterialPrice pgp
          INNER JOIN (SELECT * FROM ACME\Bundle\PricelistBundle\Entity\PricelistMaterial ORDER BY id DESC)
          WHERE pr.pricelist = :pricelist AND pgp.year <= :year
          AND pgp.week <= :week
          GROUP BY pgp.pricelistmaterial
          ORDER BY pgp.year DESC, pgp.week DESC, pgp.id DESC
        ')->setParameters(array('pricelist' => $pricelist, 'week' => $week, 'year' => $year));

        $result = $query->getResult();

        return $result;
    }

但是我认为,连接中的子查询是不可能的,因为这给了我错误:

[Semantical Error] line 0, col 119 near '"(SELECT * FROM': Error: Class '"' is not defined.

有人能指出我正确的方向吗?

3 个答案:

答案 0 :(得分:0)

您的子查询附近有一个不需要的双引号:

      INNER JOIN "(SELECT * FROM ACME\Bundle\PricelistBundle\Entity\PricelistMaterial ORDER BY id DESC)"

而不是

      INNER JOIN (SELECT * FROM ACME\Bundle\PricelistBundle\Entity\PricelistMaterial ORDER BY id DESC)"

答案 1 :(得分:0)

您在pr.prijslijst子句中使用WHERE但从未定义过它。我不懂语言(荷兰语?)但如果prijslijstPricelistMaterial的属性,那么修改这样的子查询应该有效:

SELECT pr FROM ACME\Bundle\PricelistBundle\Entity\PricelistMaterial pr ORDER BY pr.id DESC

此外,您的参数键错误 - 它们似乎在查询中用荷兰语编写,但在setParameter方法中用英语编写。

答案 2 :(得分:0)

我通过思考一点点找到了解决方案。

这最终是功能:

public function getPriceLines($pricelinematerial = 0, $year = 0, $week = 0)
    {
        if ($year === 0) {
            $year = (int)date('Y');
        }

        if ($week === 0) {
            $week = (int)date('W');
        }

        $query = $this->getEntityManager()->createQuery('
            SELECT pgp FROM ACME\Bundle\PricelistBundle\Entity\PricelistMaterialPrice pgp
            WHERE pgp.pricelistmaterial = :pricelistmaterial AND pgp.year <= :year
            AND pgp.week <= :week
            ORDER BY pgp.year DESC, pgp.week DESC, pgp.id DESC

        ')->setParameters(array('pricelistmaterial' => $pricelistmaterial, 'week' => $week, 'year' => $year));

        $query->setMaxResults(1);
        try {
            $result = $query->getSingleResult();
        } catch (\Doctrine\ORM\NoResultException $e) {
            $result = null;
        }
        return $result;
    }