这可能是使用$virtualFields:
在投票模式中,我添加以下虚拟字段:
var $virtualFields = array(
'vote_count' => 'IFNULL(SUM(Vote.value) , 0)'
);
在Person模型我这个检索使用以下$的hasMany关系,每次:
var $hasMany = array('Vote' => array('fields' => array('vote_count')));
注意,默认情况下,它会永远在投票表中检索每一个领域,这将导致检索'vote_count'默认情况下为SUM字段,如果要完整写出查询,将只显示一行。
如果您想要检索所有行并删除SUM虚拟字段,则需要在字段数组中指定除“vote_count”字段外的所有字段(如有必要),例如
var $hasMany = array('Vote' => array('fields' => array('id', 'value')));
我建议,这是由具有在Person模型作为这样一对夫妇的功能,这将让你你如何要检索的选票飞决定更好的控制:
function allWithVoteCounts() {
$this->bindModel(array('hasMany' =>
array('Vote' => array(
'fields' => array('vote_count')
)
)
));
return $this->find('all');
}
function allVotes() {
$this->bindModel(array('hasMany' =>
array('Vote' => array(
'fields' => array('id', 'user_id', 'person_id', 'value', 'date')
)
)
));
return $this->find('all');
}
然后在控制器,你可以拨打:
$persons = $this->Person->allVotes();
或
$persons = $this->Person->allWithVoteCounts();
这是完全错误的,将尽快更新 – going