[英]How to associate models correctly cakephp
我有一个场景,其中我的模板有很多主题。 很清楚,我的关系将是模板的hasMany主题,我想告诉与主题数的模板,我将这段代码:
$this->Template->recursive = 2;
$this->Template->bindModel(
array(
'hasMany' =>array(
'TemplateTheme'=>array(
'className'=>'TemplateTheme',
'fields' => 'count(TemplateTheme.id) AS themes'
)
)
),false
);
$this->paginate = array(
'order' => array('Template.modified DESC'),
'limit' =>$limit
);
$template = $this->paginate('Template');
pr($template);die();
但我得到的是
Array
(
[0] => Array
(
[Template] => Array
(
[id] => 1
[name] => churchDesign
[status] => Active
[created] => 2011-10-24 10:37:23
[modified] => 2011-10-25 15:16:46
)
[TemplateTheme] => Array
(
[0] => Array
(
[template_id] => 1
[TemplateTheme] => Array
(
[0] => Array
(
[themes] => 3
)
)
)
)
)
[1] => Array
(
[Template] => Array
(
[id] => 2
[name] => blossoms
[status] => Active
[created] => 2011-10-19 00:00:00
[modified] => 2011-10-24 14:05:27
)
[TemplateTheme] => Array
(
)
)
)
这里的问题是要计算第一个数组(第一个模板)中的所有主题。请参见[TemplateTheme] => Array([0] => Array([themes] => 3),第三个主题实际上属于第二个模板。关系是
template_id位于主题表中,代表模板的每个主题。
模板1有2个主题,模板2nd有一个主题,当前它在第一个模板中显示所有三个主题。
我想要这样
templatename1
count of themes 1st template
template name 2
count of themes of 2nd template
请告诉我正确的方法。
如果要获取每个模板的主题数,最优雅的方法是使用counterCache 。
另一种方法是使用Containable行为,该行为仅获取所需的相关数据,然后在PHP中对获取的数据数组进行计数。 将可包含的行为附加到Template模型后,类似以下代码的代码应该可以工作:
$allTemplates = $this->Templates->find('all', array(
'contain' => 'TemplateTheme.name'
));
foreach($allTemplates as $template){
$currentThemeCount = count($template['TemplateTheme']);
foreach($template['TemplateTheme'] as $theme){
echo $theme['name'];
}
}
希望这可以对某人有所帮助。
你可以像这样计算主题数组
foreach($template as $t){
count($t['TemplateTheme'])
}
希望这可以帮助
您应该使用find('count')方法,而不是像现在那样使用虚拟的'count'字段。 例如:
$allTemplates = $this->Template->find('all');
foreach($allTemplates as $data) {
$templateCount = $this->Template->TemplateTheme->find('count', array(
'conditions' => array(
'TemplateTheme.template_id' => $data['Template']['id']
)
));
// $templateCount should now contain the count of this specific template. Foreach will continue recursion for all others.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.