2012-09-18 62 views
3

問題:CakePHP的counterCache多counterScope - 邏輯問題

我有兩個型號:經銷商,測試驅動(測試驅動通過dealer_id屬於經銷商)。我想說明有關經銷商實時統計:總(Testdrive.active = 1),處理(Testdrive.active = 1 & & Testdrive.processed = 1)...

我有大約100家經銷商和10000個testdrives 。基於計數的sql大約需要10秒(低效率)。現在我有一個每小時運行一次的cronjob,但我沒有實時統計信息。

我想是這樣的:

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' => '' 
    ) 
); 

...但我重寫了屬於關聯=>'Dealear的價值。

我可以有counterScope數組的counterCache數組嗎?

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' => '' 
    ), 
); 

回答

1

the documentation中有一個(現在)的例子。適用於問題的例子是:

class TestDrive extends AppModel { 

    public $belongsTo = array(
     'Dealer' => array(
      'counterCache' => array(
       'active' => array(
        'TestDrive.active' => 1 
       ), 
       'processed' => array(
        'TestDrive.active' => 1, 
        'TestDrive.processed' => 1 
       ) 
      ) 
     ) 
    ); 
} 

注意有沒有必要來定義默認值(classNameforeignKey等)鍵。