CakePHP数学计算领域?

时间:2009-10-20 04:11:10

标签: php sql mysql database cakephp

(数据库结构如CakePHP select default value in SELECT input

所以,我在CakePHP中有两个表:Trees和Leafs。每个Leaf的对应树都有tree_id。每个叶子也有一个数字value。我为树烘焙的默认视图只列出了表中的所有树。有没有办法将动态列添加到该视图的表中SUMS该树的所有叶子并在表中显示总和,以及另一个显示树有叶子数的字段?

示例:

Leafs

Id   |  Tree Id  |  Leaf value
-----+-----------+---------------
24   |  1        | 19
70   |  1        | 33
121  |  1        | 30

Trees

Id   |  Tree  |  Number of leafs  |  Sum of leafs  |  Actions
-----+--------+-------------------+----------------+-------------------
1    |  foo   |  120              |  7270          |  View Edit Delete
2    |  bar   |  72               |  4028          |  View Edit Delete

2 个答案:

答案 0 :(得分:4)

两个想法:

每次需要时使用Containable behavior动态获取求和字段,就像(在我的脑海中):

$this->Tree->find('all', array(
    ...
    'contain' => array(
        'Leaf' => array(
            'fields' => array('SUM(Leaf.value)'),
            'group'  => array('Leaf.tree_id')
        )
    )
);

或者在树模型中创建一个新列,如leaf_values,并在每次更改Leaf模型中的内容时更新它:

// Leaf model
function afterSave() {
    $sum = /* calculate sum */;
    $this->Tree->updateAll(
        array('Tree.leaf_values' => $sum),
        array('Tree.id' => $this->data['Leaf']['tree_id'])
    );
}

function afterDelete() {
    // same for afterDelete
}

答案 1 :(得分:0)

我认为你不能在可控制的电话中使用群组。