如何使用counterCache()跟踪CakePHP的视图计数?

时间:2012-10-14 07:51:43

标签: cakephp cakephp-2.0 counter-cache

每次用户查看提交时,我都会跟踪计数并将其与会话联系起来:

SubmissionsController:

// Count view
if ($this->Session->check('viewed_submission_' . $submissionId) !== true) {
    $clientIp = ip2long($this->request->clientIp());
    $this->SubmissionsViews->countView($submissionId, $clientIp);
    $this->Session->write('viewed_submission_' . $submissionId, true);
}

我在SubmissionsViews表中跟踪它们。

SubmissionsViews Model:

class SubmissionsViews extends AppModel {

    var $name = 'SubmissionsViews';

    var $belongsTo = array(
        'Submission' => array(
            'className' => 'Submission'
        )   
    );

    public function countView($submissionId, $clientIp) {
        $this->set('submission_id', $submissionId);
        $this->set('user_ip', $clientIp);
        $this->save($this->data);
    }   
}

我的SubmissionsView表submissions_views包含以下字段:

  • ID
  • submission_id
  • user_ip
  • 创建

我正在尝试设置counterCache以跟踪该表的添加内容,但不确定如何设置它。我目前正在我的提交模型中的$belongsTo中添加counterCache:

class Submission extends AppModel {
    var $belongsTo = array(
        'User' => array(
            'className' => 'User'
        ),
        'SubmissionsViews' => array(
            'counterCache' => true
        )   
    ); 

但它告诉我它找不到Submission.submissions_views_id。在文档中,它说的只是我需要在我的submissions表中添加一个名为submissions_views_count的字段,所以我很困惑如何使其工作?

1 个答案:

答案 0 :(得分:1)

  1. 模型名称应为单字形,因此SubmissionViews应为SubmissionView
  2. 您的关联不正确。 Submission hasMany SubmissionView,而不是belongsTo。
  3. 需要在SubmissionView的belongsTo配置内的Submission模型中指定counterCache,而不是在Submission模型文件中。请仔细阅读本手册。