问题
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.
回答1:
From CakePHP Book
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
来源:https://stackoverflow.com/questions/32948513/cakephp-3-countercache-with-belongstomany