我有这样一个疑问:
$thism = new \DateTime('first day of this month midnight');
$parameters = array('thism' => $thism, 'user' => $user,'status'=>1);
return $this->createQueryBuilder('q')
->select('count(q)')
->where('q.createdAt > :thism')
->andWhere('q.user = :user')
->andWhere('q.completed != :status')
->setParameters($parameters)
->getQuery()
->getSingleScalarResult();
这应该计算我这个月所有未完成的对象。问题在于 q.completed != :status
。这不会计算具有 completed=NULL
的对象。完成是一个 bool 值
class Quote
{
/**
* @var boolean
*
* @ORM\Column(name="completed", type="boolean", nullable=true)
*/
private $completed;
}
我做错了什么,或者为什么 Doctrine 不将 NULL 视为与 TRUE 不同?
我已经尝试将 'status'=>1
替换为 1,true,TRUE
,带引号和不带引号都没有效果。
格式化查询:
SELECT count(q0_.id) AS sclr_0 FROM quote q0_ WHERE q0_.created_at > ? AND q0_.user_id = ? AND q0_.completed <> ?
Parameters: ['2016-04-01 00:00:00', '1', 1]
SELECT count(q0_.id) AS sclr_0 FROM quote q0_ WHERE q0_.created_at > '2016-04-01 00:00:00' AND q0_.user_id = '1' AND q0_.completed <> 1;
最佳答案
MySQL 中的 Null 与 true 或 false 不同。 更多信息on MySQL official site.
转换为 SQL 的查询将是:
SELECT count(1)
FROM <some table>
WHERE completed != 1
AND createdAt > '01042016 00:00'
AND user = 'some_user'
如果你也想在 SQL 中查询空值,你应该有一个查询,例如:
SELECT count(1)
FROM <some table>
WHERE
( completed != 1 or completed is NULL)
AND createdAt > '01042016 00:00'
AND user = 'some_user'
如果您需要此列默认具有一些值 - 您可以在 MySQL 中通过在 CREATE TABLE
语句中使用 default 0
(或任何其他值)来定义它像那样:
CREATE TABLE my_table(
...
completed tinyint(1) default 0
....
)
如果您这样做 - 您的查询应该可以正常工作。
关于php - Doctrine 在比较时不计算空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36721428/