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.