cakephp-3.0self-joincounter-cache

CakePHP 3 CounterCache not updating on delete with belongsToMany SelfJoinTable


CakePHP vertion: 3.3.11

CounterCache working on add method but not working on delete method.

SentenceTable

    $this->belongsToMany('Sentences', [
        'foreignKey' => 'second_sentence_id',
        'targetForeignKey' => 'sentence_id',
        'joinTable' => 'sentences_sentences'
    ]);
    $this->belongsToMany('SecondSentences', [
        'className' => 'Sentences',
        'foreignKey' => 'sentence_id',
        'targetForeignKey' => 'second_sentence_id',
        'joinTable' => 'sentences_sentences'
    ]);

SentencesSentencesTable

    $this->belongsTo('Sentences', [
        'foreignKey' => 'sentence_id',
        'joinType' => 'INNER'
    ]);
    $this->belongsTo('SecondSentences', [
        'className'=>'Sentences',
        'foreignKey' => 'second_sentence_id',
        'joinType' => 'INNER'
    ]);

    $this->addBehavior('CounterCache', ['Sentences' => ['ver_count']]);

SentencesController Add method updating ver_count

$sentence = $this->Sentences->get($this->request->data['id']);
$sentence = $this->Sentences->patchEntity($sentence, $this->request->data);
            $this->Sentences->SecondSentences->saveStrategy('append');
            $this->Sentences->save($sentence);

SentencesController delete method not updating ver_count

$sentence = $this->Sentences->SecondSentences->get($this->request->data['id'],['contain'=>['Sentences']]);
if ($sentence->user_id == $this->Auth->user('id')) {
   $this->Sentences->SecondSentences->delete($sentence);
   $sentences = $this->Sentences->get($sentence->sentences[0]->id,['contain'=>['SecondSentences']]);

// NOW I AM USING BELOW CODE FOR UPDATING VER_COUNT.
   $this->Sentences->updateAll(['ver_count'=>count($sentences->second_sentences)], ['id'=>$sentence->sentences[0]->id]);
}

Solution

  • How are your records deleted. Just as mentioned in cakephp documentation (CounterCache):

    The counter will not be updated when you use deleteAll(), or execute SQL you have written.
    

    And:

    The CounterCache behavior works for belongsTo associations only.
    

    Just confirm about that first.