CakePHP数学计算领域? [英] CakePHP mathematic-calculation field?

查看:171
本文介绍了CakePHP数学计算领域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(数据库结构如 CakePHP在SELECT输入中选择默认值

所以,我在CakePHP中有两个表:Trees和Leafs。每个Leaf对于其相应的树具有 tree_id 。每个叶也有一个数字。我烘焙树的默认视图只列出表中的所有树。是否有一种方法来为该视图的表添加一个动态列,SUMS该树的所有叶子,并显示表中的总和,以及显示树的叶数的另一个字段?

So, I have two tables in CakePHP: Trees, and Leafs. Every Leaf has a tree_id for its corresponding tree. Every leaf also has a numeric value. The default view that I baked for trees just lists all the trees in a table. Is there a way to add a dynamic column to that view's table that SUMS all the leafs of that tree and displays the sum in the table, as well as another field showing the number of leafs a tree has?

例如:

叶子

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

树木

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


推荐答案

两个想法:

使用在每次需要时动态获取汇总字段可控行为,像(我的头顶):

Fetch the summed field dynamically each time you need it using the Containable behavior, like (off the top of my head):

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

或者在树模型中创建一个新列,如 leaf_values 每次你改变Leaf模型中的一些东西:

Or create a new column in the Tree model like leaf_values and update it every time you change something in the Leaf model:

// 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
}

这篇关于CakePHP数学计算领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆