0

i have nested model structure

id
parent_id
counter
name

how to use automated counter cache

baur79
  • 273
  • 5
  • 18

1 Answers1

1

Define it in the relationship definition.

<?php

class YourModel extends AppModel {

    var $belongsTo = array(
        'ParentModel' => array(
            'foreignKey' => 'your_model_id',
            'className' => 'ParentModel',
            'counterCache' => 'counter'
            )
        )
    );
}
?>

Where 'counter' is the field in your table that contains the count.

Barry Chapman
  • 6,690
  • 3
  • 36
  • 64
  • Barry - read the page in the cookbook (or the api) - I don't think you get to pass the field name to the counterCache key. From the docs it seems to be fixed to the name of the related table (pluralized) and with _count appended to it. A quick test shows me that your code as is isn't working as expected. – Abba Bryant Apr 14 '11 at 18:07
  • From the book: counterCache: If set to true the associated Model will automatically increase or decrease the “[singular_model_name]_count” field in the foreign table whenever you do a save() or delete(). If its a string then its the field name to use. The value in the counter field represents the number of related rows. – Barry Chapman Jun 07 '11 at 14:10