【问题标题】:CakePHP mathematic-calculation field?CakePHP 数学计算领域?
【发布时间】:2009-10-20 04:11:09
【问题描述】:

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

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

示例:

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

【问题讨论】:

    标签: php sql mysql database cakephp


    【解决方案1】:

    两个想法:

    每次需要时,使用 Containable behavior 动态获取总和字段,例如(我的脑海中):

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

    或者在 Tree 模型中创建一个新列,例如 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
    }
    

    【讨论】:

      【解决方案2】:

      我认为您不能在可包含调用中使用组。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 2014-08-09
      • 2019-08-11
      • 2018-11-13
      • 2012-03-25
      • 2021-03-25
      • 1970-01-01
      相关资源
      最近更新 更多