CakePHP-Listタイプデータを構築する方法


ここでいうListタイプのデータ、すなわちkey/value対で格納されたデータは、CakePHPでは通常select、checkbox、radioのoptionsとして用いられる.
find(‘list’) keyおよびvalueは、Tableクラスで定義されたdisplayFieldおよびprimaryKeyをデフォルトで使用し、通常はidおよびnameである.
//Options
$articlesTable->find('list', [
    'limit' => 100,
    ...
]);

//Methods
$articlesTable->find('list')->limit(100);

//In ArticlesTable class
$this->setTable('articles');
$this->setPrimaryKey('id');
$this->setDisplayField('name');
//    key/value
$articlesTable->find('list', [
    'keyField' => 'id',
    'valueField' => 'title',
    'groupField' => 'author_id' //   select 
]);

//Create list data from associations that can be reached with joins
$articlesTable->find('list', [
    'keyField' => 'id',
    'valueField' => 'author_name'
])->contain(['Authors']);

combine( keyPath, valuePath, $groupPath = null) key/valueのキー値対を自由に組み合わせる効果を達成することができる.
$articlesTable->find()->combine('author_id', 'title');

//Use closures to build keys/values/groups paths dynamically
$combined = (new Collection($entities))->combine(
    'id',
    function ($entity) { return $entity; },
    function ($entity) { return $entity->date->toDateString(); }
);

// Result will look like this when converted to array
[
    'date string like 2015-05-01' => ['entity1->id' => entity1, 'entity2->id' => entity2, ..., 'entityN->id' => entityN]
    'date string like 2015-06-01' => ['entity1->id' => entity1, 'entity2->id' => entity2, ..., 'entityN->id' => entityN]
]

extract()
単一のフィールド値を取得するか、コールバック関数を使用して値をフォーマットします.
//Use toList() to get all values even if there are duplicate keys
$titles = $articlesTable->find()->extract('title')->toList();

//Use Callback function
$collection = new Collection($articles);
$authors = $collection->extract(function($article) {
    return $article->author->first_name . ' ' . $article->author->last_name;
});