【问题标题】:get count of records from associated table in cakephp 2.4从 cakephp 2.4 中的关联表中获取记录数
【发布时间】:2014-05-01 07:33:40
【问题描述】:

我刚刚创建了运行良好的示例博客应用程序。

但除此之外,我还想在博客列表页面上显示每个博客的 cmets 计数。

我怎么能得到这个?

表格是:

  1. 博客
  2. cmets

每个博客可能有很多 cmets。这是我需要获取的,即某个特定博客有多少个 cmets。

【问题讨论】:

  • 你的问题不清楚,你的表也得提一下,让我们给你解答

标签: cakephp associations cakephp-2.4


【解决方案1】:

使用计数器缓存

假设评论属于博客,一个简单的方法是使用counterCache

这意味着在您的博客表中添加一个用于存储计数的字段:

alter table blogs add comment_count int(11) default 0;

将计数器缓存添加到 cmets 的关联定义中:

class Comment extends AppModel {

    public $belongsTo = array(
        'Blog' => array(
            'counterCache' => true,
        )
    );

}

然后,无论何时创建或删除评论,都会在 blogs 表中更新 comment_count 字段值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    相关资源
    最近更新 更多