Cakephp PHP WEB開発

【Cakephp2→4】SQL条件にnullを指定する場合は「IS NOT」など明記する

※本サイトはPR表記を含みます。

Cake2 から Cake4 の移行の際、SQL処理の移行作業も必要なケースがほとんどだと思います。そこで注意したいのが、conditions(条件)を定義する際に値が null なものを指定したい場合は IS などの明記が必要になります。

以下に例を示します。

Cake2: conditionsにnullを条件とした構文

$conditions[] = ['name' => null, 'deleted' => null];
$conditions[] = ['not' => ['address' => null]];

$results = $this->Model->find('all', ['conditions' => $conditions]);

Cake2 での null の条件の時は特に IS などの明記は必要ありませんでした。

Cake4では少しお作法が変わります。

Cake4: nullを条件とする場合は IS 明記が必須

$conditions[] = ['name IS' => null, 'deleted IS' => null];
$conditions[] = ['address IS NOT' => null];

$results = $this->Models->find()->where($conditions)->all();

Cake4 では ISIS NOT の明記が必要になります。また、IN 句なども同様です。
ふとした際に躓いてしまいそうなので、注意したい所ではありますね。

-Cakephp, PHP, WEB開発
-