cakePHP的counterCache问题

时间:2009-09-17 19:27:15

标签: php cakephp

我在视频共享网站项目中有这些模型:

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

标签的counterCache不起作用。我不知道为什么当我尝试向videosTag模型添加一个beforeSave()回调时,我发现当视频保存时它没有执行(这个视频有标签,我在数据库中找到它们,所以关系如何视频标签已保存?)!!!任何机构都可以解释为什么会这样。

1 个答案:

答案 0 :(得分:2)

使用以下数据保存视频:

array(
  'Video' => array(
    ...
  ),
  'Tag' => array(
    'Tag' => array(
      ...
    ),
  ),
);
视频模型上的

不会触发VideosTag模型的beforeSave回调,因为Cake处理HABTM数据而不需要(甚至使用)join / with / through模型。

据我所知,目前没有内置功能可供您实现。

查看Counter Cache behavior for HABTM relations,可能会做你需要的事情