CakePHP 3:CounterCache与BelongsToMany [英] CakePHP 3: CounterCache with BelongsToMany
问题描述
我有一个 BelongsToMany
关联,我的表是 PostsTable
, TagsTable
和 PostsTagsTable
。
如这里在CakePHP书(关联),我有这个字段:
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
。
你能帮我吗?感谢。
CounterCache行为仅为belongsTo关联工作。例如对于Comments belongsTo Articles,您需要将CounterCache行为添加到CommentsTable,以便为Articles表生成comment_count。
虽然可以使这个工作在belongsToMany关联中。您需要在关联选项中配置的自定义通过表中启用CounterCache行为。请参阅如何配置自定义连接表使用通过选项。
UPDATE
- 烘焙您的PostsTags模型
- 在您的PostsTagsTable中添加CounterCache行为
- 使用通过选项
I have a BelongsToMany
association, my tables are PostsTable
, TagsTable
and PostsTagsTable
.
As explained here in the CakePHP book (associations), I have this fields:
tags.id, tags.tag, tags.post_count
posts_tags.id, posts_tags.tag_id, posts_tags.post_id
Everything works correctly for now.
So, as you can understand, now I want to use the tags.post_count
field with CounterCache
.
I followed the CakePHP book, but I suppose this is a special case, in fact it doesn't work by simply adding the behavior to the PostsTable
.
Can you help me? Thanks.
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.
UPDATE
- Bake your PostsTags model
- Add CounterCache behavior in your PostsTagsTable
- Use the ‘through’ Option
这篇关于CakePHP 3:CounterCache与BelongsToMany的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!