Search code examples
cakephpmodelcakephp-2.0model-associations

Find record of one type with more than one associated HABTM type


I have two models in my CakePHP application: NewsArticle and Image. Image is associated with NewsArticle using a HABTM (has and belongs to many) association, so authors can build up a gallery for an article if they wish.

On my application’s homepage I want to display the top story, which will simply be the latest published article with at least one associated image. How would I form this condition in my controller? So far, I have:

<?php
$topStory = $this->NewsArticle->find('first', array(
    'order' => array(
        'NewsArticle.created' => 'desc'
    )
));

But I am unsure how to “count” the number of Image records attached to my NewsArticle model.


Solution

  • If you must use HABTM, you'll need to do a JOIN (see CakePHP Joins).

    The reason is, normal find()s actually do separate queries, then CakePHP puts the data together before it returns it to you. If you're trying to limit the main results by the existence of sub-results, you'll need to use a JOIN.

    If you're able to get away with HasMany instead (meaning an Image would belongTo a NewsArticle), you can use CakePHP's counterCache.