当我在 cakephp 3 中执行 toArray 时,自定义查找器 returns 列表
Custom finder that returns a list when I do a toArray in cakephp 3
通过查看 this,我知道如何在 CakePHP 3.x 中编写自定义查找器。
我也知道如何使用 find('list')
获得 "list" 然后通过 this
使用 toArray
我想做的是编写一个自定义查找器,确保我可以在自定义查找器的结果上使用 toArray
,如果我使用 find('list')
,则返回一个类似的数组。
我的自定义查找器方法名称是 findListForDynamicViews
。
因此我想要
$query = $circlesTable->find('listForDynamicViews');
$data = $query->toArray(); // this gives me an associative array similar to the one we get from find('list')
如果我知道如何使用 where()
进行查询,我该如何编写自定义查找器?
这可以使用结果格式化程序实现,list
查找器也是这样做的:
剥离到最基本的东西,您只需按键和值字段组合,通常是主键和显示字段:
$query->formatResults(function(\Cake\Datasource\ResultSetInterface $results) {
return $results->combine('key_field', 'value_field');
});
也许这个简短的代码适用于您的情况:
$query = $circlesTable->find('list')->find('listForDynamicViews');
您根本不需要修改您的自定义查找器。
我设法用这样的自定义查找器做到了这一点:
// contained in my PropertiesTable.php
public function findCityList(Query $query) {
return $query->find('list', ['keyField' => 'id', 'valueField' =>'city'])
->select(['city'])->distinct(['city']);
}
对 find() 上的列表的调用已经 returns 一个数组,因此您不需要在它之后调用 toArray()。
// the retuning array
$citys = [
'7' => 'Olímpia',
'10' => 'São José do Rio Preto',
'17' => 'Guarujá'
];
希望对您有所帮助。
通过查看 this,我知道如何在 CakePHP 3.x 中编写自定义查找器。
我也知道如何使用 find('list')
获得 "list" 然后通过 this
toArray
我想做的是编写一个自定义查找器,确保我可以在自定义查找器的结果上使用 toArray
,如果我使用 find('list')
,则返回一个类似的数组。
我的自定义查找器方法名称是 findListForDynamicViews
。
因此我想要
$query = $circlesTable->find('listForDynamicViews');
$data = $query->toArray(); // this gives me an associative array similar to the one we get from find('list')
如果我知道如何使用 where()
进行查询,我该如何编写自定义查找器?
这可以使用结果格式化程序实现,list
查找器也是这样做的:
剥离到最基本的东西,您只需按键和值字段组合,通常是主键和显示字段:
$query->formatResults(function(\Cake\Datasource\ResultSetInterface $results) {
return $results->combine('key_field', 'value_field');
});
也许这个简短的代码适用于您的情况:
$query = $circlesTable->find('list')->find('listForDynamicViews');
您根本不需要修改您的自定义查找器。
我设法用这样的自定义查找器做到了这一点:
// contained in my PropertiesTable.php
public function findCityList(Query $query) {
return $query->find('list', ['keyField' => 'id', 'valueField' =>'city'])
->select(['city'])->distinct(['city']);
}
对 find() 上的列表的调用已经 returns 一个数组,因此您不需要在它之后调用 toArray()。
// the retuning array
$citys = [
'7' => 'Olímpia',
'10' => 'São José do Rio Preto',
'17' => 'Guarujá'
];
希望对您有所帮助。