0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CakePHPのCounterCache

Last updated at Posted at 2022-04-16

CounterCacheとは

例えば

  • 記事の情報をもつArticleテーブル
  • 記事に対するコメントをもつCommentテーブル

がある場合、1つの記事に対するコメント数を自動で集計してくれる。

CounterCacheはbelongsToのモデルに使える。親テーブル側にcomment_countのカラムを用意しておき、子テーブルのモデルにCounterCacheを追加する。

class CommentsTable extends Table
{
    public function initialize(array $config)
    {
        $this->addBehavior('CounterCache', [
            'Articles' => ['comment_count']
        ]);
    }
}

カウントする条件を指定する

削除フラグのデータをカウントから除外したい場合。

$this->addBehavior('CounterCache', [
        'Articles' => [
            'comment_count' => [
                'conditions' => ['Comments.is_deleted' => false]
            ]
        ]
    ]);

複数のCounterCacheを持つ

記事に対するReactionテーブルが合った場合、それぞれのリアクションをカウントする。

Reactions.php
$this->addBehavior('CounterCache', [
        'Articles' => [
            'like_count' => [
                'conditions' => ['Reactions.type' => 1]
            ],
            'read_count' => [
                'conditions' => ['Reactions.type' => 2]
            ],
        ]
    ]);

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?