在cakephp中使用Counter缓存进行HABTM关联

时间:2013-01-10 06:42:44

标签: cakephp cakephp-2.1 cakephp-appmodel

我有两张桌子: 它的定义如下:

CREATE TABLE IF NOT EXISTS `users_correlations` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `correlated_id` int(11) NOT NULL,
  `type` char(1) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(100) NOT NULL,
  `first_name` varchar(50) NOT NULL,
  `last_name` varchar(50) NOT NULL,
  `password` varchar(100) NOT NULL,
  `role` varchar(2) NOT NULL,
  `gender` char(1) NOT NULL,
  `dob` date DEFAULT NULL,
  `location` varchar(100) NOT NULL,
  `photo` varchar(255) NOT NULL,
  `photo_dir` varchar(255) NOT NULL,
  `about_me` tinytext,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `modified` datetime NOT NULL,
  `follower_count`  INT DEFAULT 0,
  `following_count` INT DEFAULT 0,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=42 ;

现在我将HABTM协会定义如下:

 public $hasAndBelongsToMany=array(

      'Following'=>array(
               'className'=>'User',
               'joinTable'=>'users_correlations',
               'ForeignKey'=>'correlated_id',
               'associationForeignKey' => 'user_id'
       ),
       'Followers'=>array(
                'className'=>'User',
                'joinTable'=>'users_correlations',
                'ForeignKey'=>'user_id',
                'associationForeignKey' => 'correlated_id'
        )
    ); 

现在我想实施Countercache来跟踪追随者数量的记录并跟踪..

我对

引用的模型使用ConterCacheHabtm行为

http://bakery.cakephp.org/articles/danaki/2009/05/29/counter-cache-behavior-for-habtm-relations

但是对于我的关联,它不会更新我的follower_count和following_count。 请在这种情况下提供帮助。

1 个答案:

答案 0 :(得分:0)

 'Followers'=>array(
            'className'=>'User',
            'joinTable'=>'users_correlations',
            'ForeignKey'=>'user_id',
            'associationForeignKey' => 'correlated_id',
            'counterCache' => true
        )

您需要将'counterCache' => true添加到数组中。其余的看起来应该可以正常工作。