37
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CakePHP3のORMにおけるIN句とNOT句の記述方法

Last updated at Posted at 2015-09-24

INだけだとググラビリティ低くて情報に行き着くまで時間がかかったのでQiitaにも載せておきます。
今後こういう記事を幾つか書くと思います。

Where In

http://book.cakephp.org/3.0/en/orm/query-builder.html#automatically-creating-in-clauses

use Cake\ORM\TableRegistry;

$users = TableRegistry::get('User')->find()
    ->where(['User.id IN' => [1, 2, 3]])
    ->all();

CakePHP2.x系までは条件式のvalueに配列を指定すると自動的にINに切り替わりましたが、
CakePHP3.x系ではbooleanとして解釈され1に変換されます。
idが1のデータが存在するとデータが取れてしまうため案外気付きにくい箇所かもしれません。

Where Not

http://book.cakephp.org/3.0/en/orm/query-builder.html#automatic-is-not-null-creation

use Cake\ORM\TableRegistry;

// IS NOT
$users = TableRegistry::get('User')->find()
    ->where(['User.id IS NOT' => 1])
    ->all();

// !=
$users = TableRegistry::get('User')->find()
    ->where(['User.id !=' => 1])
    ->all();

// INの時
$users = TableRegistry::get('User')->find()
    ->where([
        'NOT' => ['User.id IN' => [1, 2, 3]]
    ])
    ->all();

CakePHP2.x系と同じような否定式が使えます。
INの時はNOTをキーにしてその下に条件式を配置してあげれば上手くいきます。

37
38
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
37
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?