views:

567

answers:

2

(Database structure like http://stackoverflow.com/questions/1545764/cakephp-select-default-value-in-select-input)

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?

example:

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
+3  A: 

Two ideas:

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')
        )
    )
);

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
}
deceze
A: 

I don't think you can use group within containable calls.

Abba Bryant
1.3 should have support for this: http://teknoid.wordpress.com/2009/10/06/top-10-things-to-look-forward-to-in-cakephp-1-3/
deizel