2009-09-17 68 views
0

的counterCache我有一个视频共享网站项目的机型如下:问题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的标签不工作。我不知道为什么,当我试图添加一个beforeSave()回调到videosTag模型时,我发现它不会在视频被保存时执行(并且此视频有标签,并且我在数据库中找到它们,所以关系videosTags已保存?)!!!任何人都可以解释为什么会发生这种情况

+0

你是如何保存数据?只有在使用'VideosTag'模型保存记录时,''VideosTag'模型'beforeSave'才会被触发,但可能不会通过'$ this-> Tag-> saveAll'来触发。 – deceze 2009-09-18 03:37:57

+0

我不知道它是如何保存的,因为cakePHP生成的每一件事,因为视频模型与标签的HABTM关系的videosTags得到保存。 – Ayoub 2009-09-18 10:18:46

回答

2

保存视频数据是这样的:

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

在视频模式将不会触发对VideosTag模型beforeSave回调,因为蛋糕处理HABTM数据,而无需(甚至使用)的加入/带/通过模型。据我所知,没有内置的功能可以实现你想要实现的功能。

检出Counter Cache behavior for HABTM relations,可能做你需要的东西