CakePHP counterCache in belongsTo (HABTM)

571 views Asked by At

i have the following Model structure.

Post

id, title, text, etc.

Tag

id, name, posts_count, created

tags_posts

id, tag_id, post_id, created

Tag Model:

public $hasAndBelongsToMany = array(
        'Post' =>
        array(
                'className' => 'Post,
                'joinTable' => 'tags_posts',
                'foreignKey' => 'tag_id',
                'associationForeignKey' => 'post_id',
                'unique' => true,
                'conditions' => '',
                'fields' => '',
                'order' => '',
                'limit' => '',
                'offset' => '',
                'finderQuery' => ''
        )
);

Post Model:

public $hasAndBelongsToMany = array(
        'Tag' =>
        array(
                'className' => 'Tag',
                'joinTable' => 'tags_posts',
                'foreignKey' => 'post_id',
                'associationForeignKey' => 'tag_id',
                'unique' => true,
                'conditions' => '',
                'fields' => '',
                'order' => '',
                'limit' => '',
                'offset' => '',
                'finderQuery' => ''
        )
);

TagsPost Model:

public $belongsTo = array(
    'Tag' => array(
        'className' => 'Tag',
        'foreignKey' => 'tag_id',
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'counterCache' => 'posts_count'

    ),
    'Post' => array(
        'className' => 'Post',
        'foreignKey' => 'post_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);

Why is the counterCache in the belongsTo of the TagsPost Model not working? I want to increase the posts_count in Tag Model, if a Post with related tags was posted and decrease if a post is deleted.

1

There are 1 answers

1
Prakash Saini On

To update counter cache in tag model, need to update tag model like as

public $belongsTo = array(
'Post' => array(
    'className' => 'Post',
    'foreignKey' => 'post_id',
    'conditions' => '',
    'fields' => '',
    'order' => '',
    'counterCache' => 'posts_count'

)

);