Skip to content

Instantly share code, notes, and snippets.

@martinbean
Last active December 10, 2015 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save martinbean/4401761 to your computer and use it in GitHub Desktop.
Save martinbean/4401761 to your computer and use it in GitHub Desktop.
Fetching records from one table based on existence of records in a HABTM relation.
<?php
class NewsArticle extends AppModel {
public $name = 'NewsArticle';
public $hasAndBelongsToMany = array(
'Image' => array(
'joinTable' => 'news_articles_images'
)
);
public function findWithImage($type, $options = array()) {
$options['joins'] = array(
array(
'table' => 'news_articles_images',
'alias' => 'NewsArticlesImage',
'type' => 'inner',
'conditions' => array(
'NewsArticle.id = NewsArticlesImage.news_article_id'
)
),
array(
'table' => 'images',
'alias' => 'Image',
'type' => 'inner',
'conditions' => array(
'NewsArticlesImage.image_id = Image.id'
)
)
);
return $this->find($type, $options);
}
}
<?php
class NewsArticlesController extends AppController {
public function home() {
$topStory = $this->NewsArticle->findWithImage('first');
$this->set('topStory', $topStory);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment