CakePHP 3:带有 BelongsToMany 的 CounterCache
CakePHP 3: CounterCache with BelongsToMany
我有一个 BelongsToMany
协会,我的表是 PostsTable
、TagsTable
和 PostsTagsTable
。
如here in the CakePHP book (associations)所述,我有以下字段:
tags.id, tags.tag, tags.post_count
posts_tags.id, posts_tags.tag_id, posts_tags.post_id
目前一切正常。
所以,正如您所理解的,现在我想将 tags.post_count
字段与 CounterCache
.
一起使用
我遵循了 CakePHP book,但我想这是一个特例,实际上它并不能通过简单地将行为添加到 PostsTable
.
你能帮帮我吗?谢谢。
The CounterCache behavior works for belongsTo associations only. For example for “Comments belongsTo Articles”, you need to add the CounterCache behavior to the CommentsTable in order to generate comment_count for Articles table.
It is possible though to make this work for belongsToMany associations. You need to enable the CounterCache behavior in a custom through table configured in association options. See how to configure a custom join table Using the ‘through’ Option.
更新
- 烘焙你的 PostsTags 模型
- 在您的 PostsTagsTable 中添加 CounterCache 行为
- Use the ‘through’ Option
我有一个 BelongsToMany
协会,我的表是 PostsTable
、TagsTable
和 PostsTagsTable
。
如here in the CakePHP book (associations)所述,我有以下字段:
tags.id, tags.tag, tags.post_count
posts_tags.id, posts_tags.tag_id, posts_tags.post_id
目前一切正常。
所以,正如您所理解的,现在我想将 tags.post_count
字段与 CounterCache
.
我遵循了 CakePHP book,但我想这是一个特例,实际上它并不能通过简单地将行为添加到 PostsTable
.
你能帮帮我吗?谢谢。
The CounterCache behavior works for belongsTo associations only. For example for “Comments belongsTo Articles”, you need to add the CounterCache behavior to the CommentsTable in order to generate comment_count for Articles table. It is possible though to make this work for belongsToMany associations. You need to enable the CounterCache behavior in a custom through table configured in association options. See how to configure a custom join table Using the ‘through’ Option.
更新
- 烘焙你的 PostsTags 模型
- 在您的 PostsTagsTable 中添加 CounterCache 行为
- Use the ‘through’ Option