我有一个 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
关于CakePHP 3 : CounterCache with BelongsToMany,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32948513/