Cakephp3 findの使用方法
更新日 2025-06-03 20:52:36
cakephp
findの使用方法
データの取得方法による結果の違い
クエリビルダーのままの場合$recs = $this->[Tables]->find();
取得結果
debug($recs)
query => 'select...'
...
all()で取得する場合
$recs = $this->[Tables]->find()->all();
取得結果
debug($recs)
'items' => (int)0 => Object {..
配列化した場合
$recs = $this->[Tables]->find()->toArray();
取得結果
debug($recs)
(int)0 => Object {..
中身の取り出し
上記のいずれも同じように中身を取り出せるforeach ($recs as $rec) {
$name = $rec->name;
}
リストの取得
フィールド指定で取得する場合
$list = $this->[Tables]->find('list', [
'keyField' => 'key',
'valueField' => 'value',
])->toArray();
TableクラスのdisplayFieldに表示したいフィールドを設定した場合
$list = $this->[Tables]->find('list')->toArray();
combineで取得で取得する場合
$list = $this->[Tables]->find()->combine('id', 'username')->toArray();
結果の空判定
結果セット
$resultset = $this->[tables]->find()->all();
if ($resultset->isEmpty()) {
// 空の場合の処理
}
クエリビルダー
$query = $this->[tables]->find();
if ($resultset->isEmpty()) {
// 空の場合の処理
}
※Collectionのメソッドはクエリオブジェクトでも使用可能。(isEmptyでクエリが評価される)