如何计算cakephp中的重复值? [英] How to count duplicate values in cakephp?
本文介绍了如何计算cakephp中的重复值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要找出每个值重复多少次。这是我到目前为止所得到的。我想用它来计算民意调查的投票。
I need to find out how many times each value is duplicated. Here's what I've got so far. I'd like to use it for counting votes in polls.
$this->set('votes', $this->Answer->Vote->find('all', array(
'fields' => array('Vote.answer_id'),
'group' => array('Vote.answer_id HAVING COUNT(*) > 1'))));
它会向我返回重复的值,例如:
And it returns me which values are duplicated, like this:
1st answer
2nd answer
4th answer
但是我仍然需要数字,以显示重复次数。
But I still need the number, to show how many times it's duplicated. Something like this.
1st answer (5)
2nd answer (3)
3rd answer (1) // not duplicated
4th answer (8)
编辑:
解决方案对我有用的
Solution that worked for me
在控制器中:
$this->set('votes', $this->Answer->Vote->find('all', array(
'fields' => array('Vote.answer_id', 'count(*) as TotalVotes'),
'group' => array('Vote.answer_id HAVING COUNT(*) >= 1'))));
视图中:
foreach ($votes as $vote):
echo $vote[0]['TotalVotes'];
endforeach;
推荐答案
此查询将起作用。
SELECT answer_id, COUNT(*) AS TotalVotes FROM votes GROUP BY answer_id HAVING COUNT(*) > 1
CakePHP等效查找条件:
CakePHP equivalent find condition:
$result = $this->Answer->Vote->find('all', array(
'fields' => array('Vote.answer_id', 'count(*) as TotalVotes'),
'group' => array('Vote.answer_id HAVING COUNT(*) > 1')));
您将在单独的数组中找到 TotalVotes
在索引[0]
中。要解决此问题,只需在选择查询之前编写以下代码:
You will find TotalVotes
in a separate array at index [0]
. To overcome this issue, just write the following code before your select query:
$this->Answer->Vote->virtualFields['TotalVotes'] = 0;
这篇关于如何计算cakephp中的重复值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文