title: Searching in Yii with Multiple MANY_MANY Conditions
body: <p>In the Yii framework, I'm trying to figure out how to query and get back results that match multiple tags in the following system:</p>
  
  <pre><code>posts
  id
  
  tags
  id
  
  post_tags
  post_id
  tag_id
  </code></pre>
  
  <p>I'm trying to figure out how to return a result of posts which match tag 1 AND tag 2. Any help with this would be much appreciated.</p>
  
  <hr>
  
  <h2>EDIT</h2>
  
  <p>So far I seem to have it working like this:</p>
  
  <p>In <code>Post</code> relations:</p>
  
  <pre><code>array(
      'tags'  =&gt; array( self::MANY_MANY, 'Tag', Yii::app()-&gt;db-&gt;tablePrefix . 'post_tag(post_id,tag_id)' ),
  );
  </code></pre>
  
  <p>In <code>PostTag</code> relations</p>
  
  <pre><code>array( 
      'post'  =&gt; array( self::BELONGS_TO, 'Post', 'post_id' ),
      'tag'   =&gt; array( self::BELONGS_TO, 'Tag', 'tag_id' ),
  );
  </code></pre>
  
  <p>In my <code>Controller</code></p>
  
  <pre><code>$tags   = array( 1, 2, 3 ); // Match N tags
  
  $criteria           = new CDbCriteria();
  $criteria-&gt;with = 'post';
  $criteria-&gt;addInCondition( 'tag_id', $tags );
  $criteria-&gt;group    = 'post_id';
  $criteria-&gt;having   = 'COUNT(*) = ' . count( $tags );
  
  $matchedPostTags    = PostTag::model()-&gt;findAll( $criteria );
  foreach( $matchedPostTags as $matchedPostTag )
  {
      $post   = $matchedPostTag-&gt;post;
      // Do what you want with it.
  }
  </code></pre>
  
  <p>Now if anyone can figure out how to get this working with CActiveDataProvider I would appreciate it.</p>