0

I have an Artist model and a Product model. Their associations are as follows:

Artist hasMany Product Product belongsTo Artist 

An Artist may not have any Products. How do I use the find() method to list all artists along with the number of Products they have?

1
  • did you mean the "COUNT()" of products?? Commented Nov 23, 2011 at 16:44

4 Answers 4

1

as long as your relationships are set up properly, this is all you need to do.

$results = $ArtistModel->find('all'); 
Sign up to request clarification or add additional context in comments.

Comments

1

From artist controller you can do this:

$this->Artist->find('all') 

To access it in a view you will need to use set() like this:

$this->set('artists', $this->Artist->find('all')); 

You can then see the data by doing print_r($artists); in a view.

Comments

1

You can use a simple find call like this:

$artists = $this->Artist->find('all'); 

which returns and array like this:

array( [0] => array( [Artist] => array( 'id' => 1, 'other_field' => 'other_value', ... ), [Product] => array( [0] => array( 'id' => 1, ... ), [1] => array( 'id' => 2, ... ) ) ) [1] => array( [Artist] => array( 'id' => 2, 'other_field' => 'other_value', ... ), [Product] => array(...) ) ) 

You can then iterate over the results and get the information you need:

foreach ( $artists as $artist ) { echo $artist['Artist']['name']; echo count($artist['Product']); } 

Comments

0

You could use the counterCache function to store on cache the number of products per Artist.

Or if you want to, you could (manually) use the ORM, it should be something like:

$this->Artist->find('all',array('fields'=>array('Artist.*','COUNT(Product.id) as count_products') 'joins'=>array(array('table' => 'products', 'alias' => 'Product', 'type' => 'INNER', 'conditions' => array('Artist.id = Product.artist_id'))), 'group'=>'Artist.id' )); 

Hope this helps

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.