CakePHP - 构建List类型数据的方式

这里所指的List类型数据,即以 key/value 对形式存储的数据,在CakePHP中此类数据通常作为select、checkbox、radio的options使用。

find(‘list’)

keyvalue 默认使用Table类中定义的 displayFieldprimaryKey,通常为 idname

//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;
});

你可能感兴趣的:(CakePHP,find,extract,toList,combine,CakePHP)