tags:

views:

50

answers:

2

Hi folks,

I'm trying to join a model through a hasmany association and then count the number of records. Basically I have users and projects. I want to display the number of associated projects on the user index action.

var $hasMany = array('Project' => 
                                array('className'     => 'Project', 
                                      'conditions'    => '',
                                      'order'         => '', 
                                      'limit'         => '',                    
                                      'foreignKey'    => 'user_id',              
                                      'dependent'     => true,                   
                                      'exclusive'     => false,                  
                                      'finderQuery'   => '',                      
                                      'fields'        => '',                      
                                      'offset'        => '',                      
                                      'counterQuery'  => '',
                                      'counterCache'  => true
                                      )           
                    );

So I have joined to Project model on user_id and have set the counterCache to true. The question is how do I access this in the user index view?

I've tried

<?php echo $user['Project']['project_count']; ?>

and

<?php echo $user['User']['project_count']; ?>

Can someone help me?

Jonesy

+1  A: 

counterCache need to be in the belongsTo association. In your example you need to have

project_count in the users table while in the project model's association belongsTo you need to activate the counterCache to true. Check the manual

Nik
Hi I have enabled the counterCache in the projects model and am trying to access it using <?php echo $user['User']['project_count']; ?> when I view the sql dump I actually don't see the Count function being called
iamjonesy
+1  A: 

If you've done all that and the project_count is still not updating, try turning off caching in app/config/core.php

I ran into that issue when I updated the database schema but Cake was caching the old schema and thus no counter field was found.

WiseOwl9000
sorry forgot to update this question. Stupidly I hadn't added the count field to my project table. I know right :(
iamjonesy