$result = $this->er->createQueryBuilder("r")
->select("COUNT(r.customer IS NOT NULL) as customers")
->getQuery()
->getResult(AbstractQuery::HYDRATE_ARRAY);
I'm trying to run this query using Doctrine Query Builder but it returns this error: Doctrine\ORM\Query\QueryException [Semantical Error] ...: Error: Class 'NULL' is not defined. when using NULL
What am I doing wrong? How can I implement IS NOT NULL
into my query?
Also, please consider this:
$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);
Therefore, adding ->where("r.customer IS NOT NULL")
would't work much here. My first question wasn't defined precisely. I'm sorry about that.
This solution works for me:
$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);
Try this
$result = $this->er->createQueryBuilder("r")
->select("COUNT(*) as customers")
->where("r.customer IS NOT NULL")
->getQuery()
->getResult(AbstractQuery::HYDRATE_ARRAY);
EDIT :
If you want a more complex request
$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);