On Mar 27, 5:12 pm, Maldras <miguel.he...@gmail.com> wrote: > I'm trying to get a List of posts and the number of related comments. > Using find('count') for each post is unelegant and adds unnecessary > overhead, and I don't want to add a new field to the database to use > counterCache. > Is there any way to solve this with cakePHP under these conditions? > Using sql it would be just a "join" with a "group by"... I'm new to > all these ORM problems (and solutions). > Thank you.
There may be a way to generalize the code below, but I haven't had the time to do that though. However, I think this code should get what you want (adjust Post.* to fit your Post field needs), provided you have the Containable behavior set up for the model(s) involved: $results = $this->Post->find('all', array('fields' => array('Post.*'), 'contain' => array('Comment' => array('fields' => array('COUNT (Comment.id) AS NumComments'))), 'group' => 'Post.id')); $count = count($results); for ($i = 0; $i < $count; $i++) { if (!empty($results[$i]['Comment'])) $results[$i]['Post']['NumComments'] = $results[$i]['Comment'][0] ['Comment'][0]['NumComments']; else $results[$i]['Post']['NumComments'] = 0; unset($results[$i]['Comment']); } I tried this code out locally and it works for the situation you described. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "CakePHP" group. To post to this group, send email to cake-php@googlegroups.com To unsubscribe from this group, send email to cake-php+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php?hl=en -~----------~----~----~----~------~----~------~--~---