问题描述
我有两个比较表,如下所示:
I have Two diff tables as given below:
用户和帖子
根据帖子数量表排序
关系定义为:
User Model:
public $hasMany = array('Post');
Post Model
Public $belongsTo = array('User');
推荐答案
counterCache - / strong>
counterCache - Cache your count()
此函数可帮助您缓存相关数据的计数。不是通过 find('count')手动计数记录,模型本身会跟踪对相关 $ hasMany 模型的任何添加/删除,并增加/减少专用整数字段
This function helps you cache the count of related data. Instead of counting the records manually via find('count'), the model itself tracks any addition/deleting towards the associated $hasMany model and increases/decreases a dedicated integer field within the parent model table.
字段的名称由单个模型名称后跟下划线和单词count组成:
The name of the field consists of the singular model name followed by a underscore and the word "count":
my_model_count
具有名为 ImageComment 的模型和名为图像的模型,则可以向图像表中添加一个新的INT字段,并将其命名为 image_comment_count 。
Let’s say you have a model called ImageComment and a model called Image, you would add a new INT-field to the image table and name it image_comment_count.
一旦你添加了计数器字段,你就可以去了。通过添加 counterCache 键并将值设置为 true ,在关联中启用计数器缓存:
Once you have added the counter field you are good to go. Activate counter-cache in your association by adding a counterCache key and set the value to true:
<?php
class Image extends AppModel {
public $belongsTo = array(
'ImageAlbum' => array('counterCache' => true)
);
}
从现在开始,每次添加或删除 / strong>关联到 ImageAlbum , image_count 中的数字会自动调整。
From now on, every time you add or remove a Image associated to ImageAlbum, the number within image_count is adjusted automatically.
> counterScope 。它允许你指定一个简单的条件,告诉模型什么时候更新(或者什么时候不会,取决于你如何看待它)计数器值。
You can also specify counterScope. It allows you to specify a simple condition which tells the model when to update (or when not to, depending on how you look at it) the counter value.
使用我们的图像模型示例中,我们可以像这样指定:
Using our Image model example, we can specify it like so:
<?php
class Image extends AppModel {
public $belongsTo = array(
'ImageAlbum' => array(
'counterCache' => true,
'counterScope' => array('Image.active' => 1) // only count if "Image" is active = 1
));
}
这篇关于基于相关表数据的计数的订单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!