【发布时间】:2013-09-13 09:38:05
【问题描述】:
好的,这是我的表/模型结构:模型已适当关联。
我正在尝试查询给定客户 ID 的 持有价值总和,并将给定价值总和的日期作为数组键。
我查阅了文档,我在客户端模型中为我的查询生成了以下参数:
$findParameters = array(
'conditions' => array(
'Account.client_id' => $clientId,
'Holding.holding_date = LAST_DAY(Holding.holding_date)', //gets month-end dates only
'MONTH(Holding.holding_date)' => array(3,6,9,12) //Use for quarter-end dates
),
'fields' => array(
'Holding.holding_date',
'SUM(Holding.value) AS portfolio_value'
),
'group' => array('Holding.holding_date')
);
当我运行查询时
$holdings = $this->Account->Holding->find( 'all', $findParameters );
我得到这样的结果:
Array
(
[0] => Array
(
[Holding] => Array
(
[holding_date] => 2009-12-31
)
[0] => Array
(
[portfolio_value] => 273239.07
)
)
[1] => Array
(
[Holding] => Array
(
[holding_date] => 2010-03-31
)
[0] => Array
(
[portfolio_value] => 276625.28
)
)
...
这很好,但我想要这样的数组中的结果:
Array (
[2009-12-31] => 273239.07
[2010-03-31] => 276625.28
...
)
所以我尝试这样做:
$holdings = $this->Account->Holding->find( 'list', $findParameters )
但我得到了错误:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Account.client_id' in 'where clause'
查询看起来好像不再对表执行连接。知道为什么,如果我使用all 而不是list 效果很好?以及如何获得我想要的结果?
编辑:我已经使用 Cake 的 hash 类实现了我的结果,但我想知道直接查询是否是一种更优越、更有效的方法。
我的方法:
$holdings = $this->Account->Holding->find( 'all', $findParameters );
$values = Hash::extract($result, '{n}.0.portfolio_value');
$dates = Hash::extract($result, '{n}.Holding.holding_date');
$result = array_combine($dates, $values);
return $result;
【问题讨论】:
-
哈哈,我也用哈希技巧完成了我的回答。很好,你自己找到了 ;) -edit:实际上,我以不同的方式做,但
Hash::combine正在做你所做的事情:2 次提取和一次合并。