Tuesday, December 22, 2009

Re: Count column in index view

Jamal - I really appreciate your reply - thank you.

This approach might well work, but I am sure there must be a simpler
way. I want to make the database do as little work as possible. In
plain old SQL I can do this:

SELECT a.id, a.name
count(b.id) as subCount
from tablea a
left join tableb b
on (b.type_id = a.id)
group by (a.id)

...which returns me all of the rows in tablea with an extra column
that shows me the count of rows in tableb that have the type_id in the
row. One query and bosh I have my results with the count.

How do I do this in Cake?

On Dec 22, 9:13 am, Jamal Aziz <jamalsaepula...@gmail.com> wrote:
> Hi Jeremy,
>
> I think you can do that in your model with afterFind callback. For
> example:
>
> class MyModel extends AppModel{
>         var $actsAs = array('Tree');
>
>         function afterFind($results, $primary){
>                 // for multiple result
>                 if(is_array($results)){
>                         if(is_array($results[0])){
>                                 foreach($results as $key => $val){
>                                         $results[$key][$this->alias]['childCount'] = $this->childCount
> ($results[$key][$this->alias][$this->primaryKey]);
>                                 }
>                         } else { // for single result
>                                 $results[$this->alias]['childCount'] = $this->childCount($results
> [$key][$this->alias][$this->primaryKey]);
>                         }
>                 }
>     }
>
> }
>
> Note: I am not test this code myself.
>
> Hope this help.

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: