cakephp3 findの使用方法

更新日 2021-07-30 16:39:24
cakephp3
検索

// クエリビルダー
$recs = $this->[Tables]->find();
// データ取り出し
foreach($recs as $rec) {
  $rec->fieldname;
}

// 中身
debug($recs)
↓
query => 'select...'
...

// クエリビルダー->all()
$recs = $this->[Tables]->find()->all();
// データ取り出し
foreach($recs as $rec) {
  $rec->fieldname;
}
// 中身
debug($recs)
'items' => (int)0 => Object {..

// クエリビルダー->toArray()
$recs = $this->[Tables]->find()->toArray();
// データ取り出し
foreach($recs as $rec) {
  $rec->fieldname;
}
// 中身
debug($recs)
(int)0 => Object {..
リスト

// クエリビルダー
$list = $this->[Tables]->find('list', ['keyField' => 'key', 'valueField' => 'value'])->toArray();
// 中身
debug($list);
1 => taro,
2 => jiro,

// クエリビルダー
$list = $this->[Tables]->find('list')->toArray();
// 中身
debug($list);
// ※TableクラスのdisplayFieldに表示したいフィールドを設定しておく
1 => taro,
2 => jiro,

// combine
$list = $this->[Tables]->find()->combine('id', 'username')->toArray();
// 中身
debug($list);
1 => taro,
2 => jiro,

空判定

// 結果セット
$resultset = $this->[tables]->find()->all();
// 空判定
$resultset->isEmpty();

// クエリオブジェクト
$query = $this->[tables]->find();
// 空判定
$query->isEmpty();

※Collectionのメソッドはクエリオブジェクトでも使用可能。(isEmptyでクエリが評価される)