Home N-13 News Forums Help Search
RegisterForgot password?
How to add image to post necklacesdiscou
Known bugs - 4.0.3 necklacesdiscou

Latest N-13 News 4.0.3

What is N-13 News?
Where can I get help?
Known bugs

Forums Tutorials CakePHP - Multiple counterCache fields on the same model
Chris
Posted on 21 Dec 2011, 00:55:47

Access: Admin
Total Posts: 1395
Joined: 2006-05-19

Adding a counterCache field to your model if CakePHP is fairly straight forward, what may not be as straight forward is adding a second counterCache field to the same model.

Take this scenario, you have a standard forum, each forum category has a counterCache field to count the amount of threads for that category

<?php
class Thread extends AppModel {
    public $name = 'Thread';

    public $belongsTo = array(
        'SubForum' => array(
            'counterCache' => true,
            'foreignKey' => 'sub_forum_id',
            'className' => 'SubForum',
            'counterScope' => array('Thread.thread_id' => 0)
        )
    );
}

This is your standard counterCache implementation, Thread belongs to SubForum, the thread_count field in the SubForum model will automatically update every time a new thread is posted.

Now say wanted to add a second field to the SubForum model, a field to count the total threads with certain conditions, for example you want one counterCache field to count the total threads and a second to count the total threads & replies (total posts) to each of those threads.

<?php
class Thread extends AppModel {
    public $name = 'Thread';

    public $belongsTo = array(
        'SubForum' => array(
            'counterCache' => true,
            'foreignKey' => 'sub_forum_id',
            'className' => 'SubForum',
            'counterScope' => array('Thread.thread_id' => 0)
        ),
        'SubForum2' => array(
            'counterCache' => 'total_thread_count',
            'foreignKey' => 'sub_forum_id',
            'className' => 'SubForum',
            'counterScope' => array('Thread.thread_id <> 0'),
    );
}

Here we've said that the Thread has multiple relations to the SubForum, defining the second relation as SubForum2. The counterCache field in the second relation, instead of simply being set to true can be set to the column name you want to update.

#3646
Last edited by Chris at 2011-12-31 16:06:53 Reason: Formatting
Network-13.com © 2013