I'm coding a tagging system in CakePHP (latest release) but the solution I have made seems over complicated compared to how easy the rest of CakePHP is. Hopefully someone can point me in the right direction or help me improve my current solution.
I need to pass to my view data in this format (JSON):
[{label:'actionscript', count: 14}, {label:'php', count: 2} ... ]
Now I know the following SQL query gives me the needed data:
SELECT tags.name, count(*)
FROM tags
RIGHT JOIN tags_users
ON tags.id=tags_users.tag_id
GROUP BY name";
So using CakePHP find method I made:
$options = array();
$options['contain'] = '';
$options['recursive'] = -1;
$options['joins'][0]['table'] = 'tags_users';
$options['joins'][0]['type'] = 'RIGHT';
$options['joins'][0]['conditions'] = 'Tag.id = tags_users.tag_id';
$options['fields'] = array('name', 'COUNT(*) as tag_counter');
$options['group'] = 'Tag.name';
$options['order'] = 'tag_counter DESC';
$availableTagsArray = $this->User->TagsUser->Tag->find('all', $options);
This give me an array out as:
Array
(
[0] => Array
(
[Tag] => Array
(
[name] => actionscript
)
[0] => Array
(
[tag_counter] => 14
)
)
[1] => Array
(
[Tag] => Array
(
[name] => php
)
[0] => Array
(
[tag_counter] => 2
)
)
)
I then convert this array to JSON by:
$availableTags = "[";
foreach ($availableTagsArray as $tag) {
$availableTags .= "{label:'{$tag['Tag']['name']}', count:{$tag[0]['tag_counter']}},";
}
$availableTags = substr($availableTags, 0, -1);
$availableTags .= "]";
$this->set("availableTags", $availableTags);
[UPDATE]
After doing a lot of research and using both answers. I've found there multiple ways to do this and that includes my original solution. You could also use virtual fields then the afterFind method and flattening the results there.