Reputation: 487
Problem:
I have two models: Dealer, Testdrive (Testdrive belongs to Dealer through dealer_id). I want to show real time statistics about the dealers: total (Testdrive.active = 1), processed (Testdrive.active = 1 && Testdrive.processed = 1) ...
I have approx 100 dealers and 10000 testdrives. The count based sql takes about 10 sec (inefficient). Now i have a cronjob that runs every hour but I don't have real time stats.
I tried something like this:
var $belongsTo = array(
'Dealer' => array(
'className' => 'Dealer',
'foreignKey' => 'dealer_id',
'counterCache' => 'active',
'counterScope' => array('Testdrive.active' => 1),
'conditions' => '',
'fields' => '',
'order' => ''
),
'Dealer' => array(
'className' => 'Dealer',
'foreignKey' => 'dealer_id',
'counterCache' => 'processed',
'counterScope' => array('Testdrive.active' => 1, 'Testdrive.processed' => 1),
'conditions' => '',
'fields' => '',
'order' => ''
)
);
... but i overwritten the belongsTo => 'Dealear' value.
Can I have an array of counterCache with an array of counterScope?
var $belongsTo = array(
'Dealer' => array(
'className' => 'Dealer',
'foreignKey' => 'dealer_id',
'counterCache' => array('active', 'processed'),
'counterScope' => array('active' => array('Testdrive.active' => 1), 'processed' => array('Testdrive.active' => 1, 'Testdrive.processed' => 1)),
'conditions' => '',
'fields' => '',
'order' => ''
),
);
Upvotes: 3
Views: 1533
Reputation: 66169
There's (now) an example of this in the documentation. Applied to the example in the question that would be:
class TestDrive extends AppModel {
public $belongsTo = array(
'Dealer' => array(
'counterCache' => array(
'active' => array(
'TestDrive.active' => 1
),
'processed' => array(
'TestDrive.active' => 1,
'TestDrive.processed' => 1
)
)
)
);
}
Note there's no need to define keys with default values (className
, foreignKey
etc.).
Upvotes: 1