这里所指的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的<optgroup>
]);
//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;
});