<e.blumstengel@googlemail.com> wrote:
> Hey,
>
> I was wondering the other day how can I achieve the following result
> by doing a find on a specific model:
>
> Let's say I have a table called items and they've got a foreign key to
> a category (category_id).
>
> What I want to have is a find, that picks me the 10 most used
> categories from the table items, sorted from most to less. The result
> should be:
>
> Category 5 - 11 items
> Category 2 - 7 items
> Category 9 - 3 items
> Category 1 - 2 items
> ...
>
> I think you'll get the idea. A simple key -> value array with the key
> as the category_id and the value as the count of the items would be
> all I need but it could also be an array with the name of the category
> also if someone is able to do that...
Looks like a job for counterCache:
http://book.cakephp.org/view/816/counterCache-Cache-your-count
Then your query would be a simple:
$data = $this->Category->find(
'all',
array(
'fields' => array(
'Category.id', 'Category.item_count'
),
'order' => array('Category.item_count' => 'DESC'),
'limit' => 10
)
);
You could then use Set::extract() to format the result into a simple
key => value, 1-D array.
Check out the new CakePHP Questions site http://cakeqs.org and help others with their CakePHP related questions.
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php?hl=en
No comments:
Post a Comment