문제

Every time a user views a submission, I track the count and tie it to a session:

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

I'm keeping track of them in a SubmissionsViews table.

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

My SubmissionsView table submissions_views has the following fields:

  • id
  • submission_id
  • user_ip
  • created

I'm trying to set up counterCache to keep track of additions to that table, but not sure how to set it up. I'm currently adding the counterCache in my $belongsTo within my Submission model:

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

But it's telling me it can't find Submission.submissions_views_id. In the documentation, all it said was that I needed to add a field to my submissions table called submissions_views_count, so I'm confused how to get this working?

도움이 되었습니까?

해결책

  1. Model names should be singlular, so SubmissionViews should be SubmissionView.
  2. Your association is incorrect. Submission hasMany SubmissionView, not belongsTo.
  3. counterCache needs to be specified in the SubmissionView model inside the belongsTo config for Submission, not in the Submission model file. Please read the manual more carefully.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top