我有一个模型模板,其中有许多主题。我想显示与主题计数模板的列表。我正在使用这个
$this->Template->bindModel(
array(
'hasMany' => array(
'TemplateTheme' => array(
'className' => 'TemplateTheme',
'fields' => 'count(TemplateTheme.id) AS themes'
)
)
), false ...
它给了我2个模板。但是它给了我所有的3个主题计数在第一个模板中,而2个主题属于模板1,第三个主题属于模板2在查询中使用id in (template_id1,template_id2)知道怎么做吗?
你正在做一个常见的错误,你每次都在计数,因为你没有使用group by,你应该做的是group by Template。当你做你的搜索。Butttttttt……有很多不会做一个连接:(所以你必须强制它一点或使用一些东西,如可链接组件
例子$join = array(
array('table' => 'templateThemes',
'alias' => 'TemplateTheme',
'type' => 'LEFT',
'conditions' => array(
'Template.id = TemplateTheme.Template_id',
)
)
);
$fields = array('Template.id','count(TemplateTheme.id) AS themes');
$this->Template->find('all', array('fields'=>$fields, 'joins'=>$join', $group =>array('Template.id')));
你也可以反过来做因为belongsTo会做这样的连接
在你的模型中(总是建议把它放在你的模型中静态,除非不是一个正常的关联)
var belongsTo = array(
'Template'=> array(
'classname' => 'Template',
'foreign_key' => 'template_id'
);
和in控制器
$fields = array('Template.id','count(TemplateTheme.id) AS themes');
$this->Template->find('all', array('fields'=>$fields, $group =>array('Template.id')));
希望这对你有所帮助,如果没有的话,请评论