0

I've got the two Models: Article and Hashtag with a HABTM relation. So in my database there are the tables articles (id,text,etc.), hashtags (id,value) and the join table articles_hashtags (article_id,hashtag_id). Now I want to find all articles with a given hashtag_id together with other conditions.. My attempt was first to find all articles with a given hashtag, to save them in an array:

$this->query("SELECT * FROM articles_hashtags WHERE hashtag_id=" . $hashtagId;");

and after that find articles with the other conditions,sorting etc in a second query like this:

 $this->find('all', array('conditions' => array("Articles.id" => $articleIds),...

is it possible to find articles with a hashtag condition in one query?

tobysas
  • 308
  • 5
  • 18

1 Answers1

0

First, don't use ->query(). It's only needed if you're doing something unusual (which this isn't).

There are a number of ways you could do what you're looking to do. The easiest is probably this:

//Hashtag model
$this->find('first', array(
    'conditions' => array(
        'id' => $hashtagId
    ),
    'contain' => array(
        'Article'
    )
));

This uses CakePHP's Containable Behavior. Get used to it - it's amazing.

Or, you could use JOINs.

Or, you could create a model for your HABTM association "ArticleHashtag" and use that to retrieve either (likely using Containable again).

Dave
  • 28,833
  • 23
  • 113
  • 183
  • I updated the answer to do a 'first' find instead of an 'all' find. There's no reason for an 'all' if you're using the id as a condition. – Dave Nov 14 '14 at 16:58