(Database structure like 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
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
}
I don't think you can use group within containable calls.
精彩评论