views:

149

answers:

1

I have in a video sharing website project these models :

 class Video extends AppModel {
        var $name = 'Video';
        var $hasAndBelongsToMany = array(
         'Tag' => array(
          'className' => 'Tag',
          'joinTable' => 'videos_tags',
          'foreignKey' => 'video_id',
          'associationForeignKey' => 'tag_id',
          'unique' => true,
         )
        );
    }

    class Tag extends AppModel {
        var $name = 'Tag';

        var $hasAndBelongsToMany = array(
         'Video' => array(
          'className' => 'Video',
          'joinTable' => 'videos_tags',
          'foreignKey' => 'tag_id',
          'associationForeignKey' => 'video_id',
          'unique' => true,
         )
        );

    }



 class VideosTag extends AppModel {
        var $name = 'VideosTag';

        var $belongsTo = array(
         'Video' => array(
          'className' => 'Video',
          'foreignKey' => 'video_id',
         ),
         'Tag' => array(
          'className' => 'Tag',
          'foreignKey' => 'tag_id',
          'conditions' => '',
          'counterCache' => 'videos_tag_counter'
         )
        );
    }

The counterCache for tags is not working. I don't know why and when I tried to add a beforeSave() callback to videosTag model I found that it doesn't execute when a video get saved (and this video has tags and i find them in the database so how the relation videosTags is saved ? ) !!! can any body explain why this is happening.

+1  A: 

Saving a Video with data like this:

array(
  'Video' => array(
    ...
  ),
  'Tag' => array(
    'Tag' => array(
      ...
    ),
  ),
);

on the Video model will not trigger a beforeSave callback on the VideosTag model because Cake handles HABTM data without requiring (or even using) the join/with/through model.

There is no built in functionality for what you are trying to achieve, as far as I am aware.

Check out Counter Cache behavior for HABTM relations, might do what you need

neilcrookes