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)
EDIT: Solution that worked for me
In controller:
$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'))));
In view:
foreach ($votes as $vote):
echo $vote[0]['TotalVotes'];
endforeach;
This also works:
This query will work.
CakePHP equivalent find condition:
You will find
TotalVotes
in a separate array atindex [0]
. To overcome this issue, just write the following code before your select query:Here you can search Groups of records from multiple duplicate records