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的<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;
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值