如何与“null”(空)字段进行比较?

How to compare against fields that are `null` (empty)?

我在名为 downloads 的 CakePHP 3 应用程序中有一个 table,它有一个名为 master 的列。字段类型设置为TINYINT(1)

我可以找到 downloads.master == 1 这样的任何记录:

$query = $this->Downloads->find()->where(['master' => true]);

但是 Cake 不让我查询 downloads.master !== 1。 None 这些工作,并且所有 return 在执行查询时为空 array/object:

$query = $this->Downloads->find()->where(['master' => false]);
$query = $this->Downloads->find()->where(['master' => 0]);
$query = $this->Downloads->find()->where(['master' => null]);
$query = $this->Downloads->find()->where(['master' => '']);

你使用什么作为使这成为可能的条件?我的想法是它应该是 false,因为它与 true 相反,但是对于 CakePHP 3 中的大多数东西,他们喜欢让它变得比必要的更复杂......

我已经使用 phpMyAdmin 检查了 table 中的记录,确实有 master == 1master == null 的记录,所以 [= 的结果不是零33=].

NULL0 不同(即,从 ORM 的角度来看 booleanfalse-ish -ish 列类型)。如果您想与 NULL 进行比较,那么您必须使用 IS NULL 发出查询,这是 SQL/DBMS 要求,而不是 CakePHP 要求。

然而,

CakePHP 要求您具体说明您想要做什么,因为传递 null 并不一定意味着您要与 SQL NULL 进行比较,具体取决于在上下文中。

长话短说,使用 IS 运算符:

where(['master IS' => null])

类似地使用 IS NOT 作为否定条件。您还可以将用户输入作为值传递,ORM 将测试该值并将 ISIS NOT 运算符分别转换为 =!= 以防非 null 正在传递值。

另见