public
Last active

Fetching records from one table based on existence of records in a HABTM relation.

  • Download Gist
NewsArticle.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
<?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);
}
}
NewsArticlesController.php
PHP
1 2 3 4 5 6 7 8
<?php
class NewsArticlesController extends AppController {
public function home() {
$topStory = $this->NewsArticle->findWithImage('first');
$this->set('topStory', $topStory);
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.