CakePHP 3:CounterCache与BelongsToMany [英] CakePHP 3: CounterCache with BelongsToMany

查看:651
本文介绍了CakePHP 3:CounterCache与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

你能帮我吗?感谢。

解决方案

来自CakePHP Book


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.

解决方案

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

这篇关于CakePHP 3:CounterCache与BelongsToMany的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆