CakePHP 3: CounterCache with BelongsToMany

感情迁移 提交于 2019-12-08 02:35:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!