Doctrine \ ORM \ Query \ QueryException [语义错误] ...:错误:未定义类'NULL'。在QueryBuilder中使用NULL时

时间:2015-01-02 14:22:33

标签: php doctrine-orm

$result = $this->er->createQueryBuilder("r")
            ->select("COUNT(r.customer IS NOT NULL) as customers")
            ->getQuery()
            ->getResult(AbstractQuery::HYDRATE_ARRAY);

我尝试使用Doctrine Query Builder运行此查询,但它返回此错误:Doctrine\ORM\Query\QueryException [Semantical Error] ...: Error: Class 'NULL' is not defined. when using NULL我做错了什么?如何在查询中实现IS NOT NULL

修改

另外,请考虑一下:

$result = $this->er->createQueryBuilder("r")
                ->select(
                         "COUNT(r.customer) as customers_total", 
                         "COUNT(r.customer IS NOT NULL) as customers_set", 
                         "COUNT(r.customer IS NULL) as customers_unset"
                )
                ->getQuery()
                ->getResult(AbstractQuery::HYDRATE_ARRAY);

因此,添加->where("r.customer IS NOT NULL")会在这里起作用。我的第一个问题没有准确定义。对不起,我很抱歉。

2 个答案:

答案 0 :(得分:2)

试试这个

$result = $this->er->createQueryBuilder("r")
            ->select("COUNT(*) as customers")
            ->where("r.customer IS NOT NULL")
            ->getQuery()
            ->getResult(AbstractQuery::HYDRATE_ARRAY);

编辑:

如果您想要更复杂的请求

    $this->er->createQueryBuilder("r")
                    ->select("COUNT(r.customer) as customers_total,
COUNT(case when r.customer IS NOT NULL then 1 end) as customers_set,
COUNT(case when r.customer IS NULL then 1 end) as customers_unset
")
                    ->getQuery()
                    ->getResult(AbstractQuery::HYDRATE_ARRAY);

答案 1 :(得分:2)

此解决方案适用于我:

$result = $er
            ->createQueryBuilder("r")
            ->select("COUNT(r.customer) as customers_total")
            ->addSelect("SUM(CASE WHEN r.customer IS NOT NULL THEN 1 ELSE 0 END) as customers_set")
            ->addSelect("SUM(CASE WHEN r.customer IS NULL THEN 1 ELSE 0 END) as customers_unset")
            ->getQuery()
            ->getResult(AbstractQuery::HYDRATE_ARRAY);