I would keep the comment count in a field of its own in the posts
table (eg. comments_count), and update the value automatically
whenever a comment is saved or deleted. The beauty of this code is
that you don't need to change your controller code in any way (unless
you are updating the table using raw queries or using deleteAll(),
which doesn't use callbacks during the operation (yet)).

Please note this code is off-the-cuff and untested, but I do a similar
thing in one of my projects.


class Comment extends AppModel {

        var $name = 'Comment';
        var $belongsTo = array('Post');

        var $_tempPostId;

        function afterSave($created) {
                $this->updateCommentCount($this->data['Comment']['post_id']);
        }

        function beforeDelete() {
                $this->_tempPostId = $this->field('post_id');
                return true;
        }

        function afterDelete() {
                if ($this->_tempPostId) {
                        $this->updateCommentCount($this->_tempPostId);
                        $this->_tempPostId = null;
                }
        }

        function updateCommentCount($post_id) {
                $count = $this->findCount(array('post_id' => $post_id));
                $this->Post->save( array('id' => $post_id, 'comments_count' =>
$count) );
        }

}


Cheers,
Adam

On Nov 10, 1:55 pm, Action <[EMAIL PROTECTED]> wrote:
> I want to be able to retrieve multiple blog posts as well as the
> comment count for each post. I do not want to retrieve the comments
> themselves, just the comment count.
>
> This is what I have so far:
>
> $this->Post->unbindModel(array('hasMany' => array('Comment')));
>
> $this->set('data', $this->Post->find('all', array('order' => 'created
> DESC')));
>
> I unbound the model association so it wouldn't pull the comments in
> the query. How can I make it so the find() as also grabs the comment
> count for each post it is grabbing?
>
> If I kept the association it would work, but I would have to also pull
> all of the comment data as well, which is something I don't want to
> do.
>
> Thanks.


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Cake 
PHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/cake-php?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to