freshest
freshest

Reputation: 6241

CakePHP - Use find() method

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?

Upvotes: 0

Views: 100

Answers (4)

elitalon
elitalon

Reputation: 9447

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']);
}

Upvotes: 1

pleasedontbelong
pleasedontbelong

Reputation: 20102

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

Upvotes: 0

472084
472084

Reputation: 17885

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.

Upvotes: 1

Julien
Julien

Reputation: 282

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

$results = $ArtistModel->find('all');

Upvotes: 1

Related Questions