Last active
December 10, 2015 07:28
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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