cakephpのクエリービルダーでwhereの検索条件
こんにちは!あやんです
cakephpのクエリービルダーを利用して様々な検索条件を紹介していきます
まず検索クエリーを用意します
$query = $model->find(‘all’, $options);
$optionsの中でwhere条件や結合条件などの設定ができます。
cakephpの公式サイトでオプションで使えるプロパティー説明のリンク
https://book.cakephp.org/4/ja/orm/retrieving-data-and-resultsets.html
$optionsの中身はこのような配列となります。
$options = [
'conditions' => [],
'join' => [],
...
];
クエリーを作成するモデルのfindメソッドにあるオプションにconditionsを設定することによって様々なwhere条件を追加できます。
ケース1AND
sql例文: where a = 1 and b < 2 and c ≥ 3
$conditions['a'] = 1
$conditions['b < '] = 2
$conditions['c ≥ '] = 3
ケース2 WHERE IN
sql例文: where ids in (1, 2, 3)
$conditions['ids'] = [1, 2, 3]
ケース3 AND とORを同時に使う場合
sql例文: where a =1 and b =2 and (c = 3 or d = 4);
$conditions[‘a’] = 1
$conditions[‘b’] = 2
$conditions[‘OR’] = [
'c' => 3,
'd' => 4
]
ケース4 notが含まれてるOR
sql例文: where a =1 and b =2 and (c = 3 or f is not null);
$conditions[‘a’] = 1
$conditions[‘b’] = 2
$conditions[‘OR’] = [
'c' => 3,
'NOT' => [
'f' => null
]
]
最後に書いたい$conditionsを$optionsに設定し、クエリーを実行できます!
$options['conditions'] = $conditions;$query = $model->find(‘all’, $options);
$data = $query->all();
ちょっと複雑なwhere条件でもクエリービルダーが使えるので、cakephpの便利な機能です!