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]
],
]
]);