我有这样一个查询:
$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
的对象。Completed是一个布尔值
class Quote
{
/**
* @var boolean
*
* @ORMColumn(name="completed", type="boolean", nullable=true)
*/
private $completed;
}
我做错了什么吗?或者为什么Doctrine不认为NULL与TRUE不同?
我试过用1,true,TRUE
替换'status'=>1
,无论有没有引号,仍然没有效果。
格式化查询:
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不同。MySQL官方网站上的更多信息。
您在转换为SQL时的查询将是:
SELECT count(1)
FROM <some table>
WHERE completed != 1
AND createdAt > '01042016 00:00'
AND user = 'some_user'
如果您也想在SQL中查询null值,您应该有一个查询,例如:
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
....
)
如果您这样做,那么您的查询应该不会发生任何更改。