Cake PHP join查询作为关联数组返回

时间:2013-09-13 09:38:05

标签: php sql cakephp

好的,这是我的表/模型结构:模型是相​​关联的。

table structure

我正在尝试查询给定客户端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;

2 个答案:

答案 0 :(得分:1)

一般性评论

CakePHP的ORM非常适合轻松查找查询(包括group by sort ...)。当谈到更高级的东西时,你需要处理用PHP检索的数据或制作plain SQL Query

关于关联数组

Model::find('all')Model::find('first')将始终返回关联数组。其他find方法将返回不同类型的数组,但是您将无法使用开箱即用的模型函数获得您正在寻找的结果。

关于未添加到正确子阵列的字段

要获得SUM()AVG()COUNT()后,您可以在此处正确显示您的字段about virtual fields in SQL Queries

如何在CakePHP中提取/格式化数组

最简单的方法是使用Hash类以您希望的方式提取和格式化数据。

使用Hash::combine你可以实现你想要的目标:

$result = Hash::combine($holdings, '{n}.Holding.holding_date', '{n}.0.portfolio_value');

答案 1 :(得分:0)

请尝试

$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'),
    'contain' => array('Account),
);
相关问题