CakePHP 3 CounterCache 在使用 belongsToMany SelfJoinTable 删除时不更新

CakePHP 3 CounterCache not updating on delete with belongsToMany SelfJoinTable

CakePHP 版本:3.3.11

CounterCache 处理添加方法但不处理删除方法。

句子表

    $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'
    ]);

句子句子表

    $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 添加方法更新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 删除方法未更新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]);
}

你的记录是如何删除的。 正如cakephp文档中提到的那样(CounterCache):

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

和:

The CounterCache behavior works for belongsTo associations only.

先确认一下。