CakePHP3でSQLクエリを作成するパターンを纏めてみました。
そのSELECT編です。
目次
find
| 1 2 3 4 5 6 | $this->Hoges->find()     ->where(条件)     ->order(条件)     ->order(条件)     ->select(フィールド)     ->all() | 
WHERE区の指定方法
AND条件A
| 1 | $this->Hoges->find()->where(['Hoges.id' => 1, 'Hoges.name LIKE' => '%AAA%']); | 
AND条件B
| 1 2 | $this->Hoges->find()->where(['Hoges.id' => 1]) 						->where(['Hoges.name LIKE' => '%AAA%']); | 
出力されるSQLのWHERE区
| 1 | WHERE Hoges.id = 1 AND Hoges.name LIKE '%AAAA%'; | 
上記の記載は両方同じ出力。内部の条件はANDとなる。
OR条件A
| 1 | $this->Hoges->find()->where(['OR' => ['Hoges.id' => 1, 'Hoges.name' => 'BBB']]); | 
出力されるSQLのWHERE区
| 1 | WHERE Hoges.id = 1 AND Hoges.name LIKE '%AAAA%'; | 
AND ORの複合条件
| 1 | $this->Hoges->find()->where(['Hoges.id' => 1, 'OR' => [['Hoges.name LIKE' => '%AAAA%'], ['Hoges.name LIKE' => '%BBBB%']]]); | 
出力されるSQLのWHERE区
| 1 | WHERE Hoges.id = 1 AND (Hoges.name LIKE '%AAAA%' OR Hoges.name LIKE '%BBBB%'); | 
1件のみ取得する方法
基本的に指定が無ければ全件取得されてしまいます。
1件の指定方法には”first”を利用します。
firstを使った検索
| 1 | $this->Hoges->find()->where(['Hoges.id' => 1])->first(); | 
最後にfirst()を使用すればok。
ORDERによるソート
ORDER区による並び順も単純なので、簡単に記載します。
WHERE区に続けて、以下の記載でok。
カラム名とDESC/ASCを指定し、メソッドチェーンで複数指定が可能。
| 1 | ->order(['Hoges.id' => 'DESC']); | 
OFFSET, LIMIT
OFFSET, LIMITの記載方法も同様です。
WHERE区に続けて、以下の記載でok。
メソッドチェーンでlimit(), offset()に指定の数値を指定する。
| 1 | ->limit(100)->offset(100); | 
GROUP BY, HAVING
OFFSET, LIMITの記載方法も同様です。
| 1 | ->group(['Hoges.id'])->having(['Hoges.id >' => 100]); | 
