我为这个可怕的标题道歉,我想不出如何解释我的问题。
在我的数据库中articles,有tags,,和下表articles_tags。一篇文章可以有很多标签。
articles
tags
articles_tags
目前,我能够使用所有标签来获取所有文章,但是我希望能够基于其标签来查找文章。
我的选择很简单:
$articles = $this->Article->find('all', array( // extra condition to check for tag, maybe? 'conditions' => array('Article.status' => 'active'), 'limit' => $this->articles_per_page, 'offset' => ($page_num-1)*$this->articles_per_page ));
我从数据库中返回的信息如下:
Array ( [0] => Array ( [Article] => Array ( [id] => 1 ) [Tag] => Array ( [0] => Array ( [id] => 1 [name] => Ruby [slug] => ruby [uses] => 1 [ArticlesTag] => Array ( [id] => 1 [article_id] => 1 [tag_id] => 1 ) ) ) )
如果我只想返回带有Ruby标签的文章怎么办?
Ruby
试试这个
// In your Article model function getArticleByTagSql($tag) { $dbo = $this->getDataSource(); $subQuery = $dbo->buildStatement( array( 'fields' => array('DISTINCT(ArticlesTag.article_id)'), 'table' => "articles_tags", 'joins' => array( array('table' => 'tags', 'alias' => 'Tag', 'type' => 'INNER', 'conditions' => array('ArticlesTag.tag_id = Tag.id') ) ), 'alias'=>"ArticlesTag", 'conditions' => array("Tag.name"=>Sanitize::clean($tag_words)), 'order' => null, 'group' => "ArticlesTag.article_id" ), $this ); $subQuery = ' Article.id IN (' . $subQuery . ')'; return $dbo->expression($subQuery); } // In your Articles Controller $this->paginate['conditions'][] = $this->Article->getArticleByTagSql($tag_name); $this->paginate['conditions'][] = array('Article.status' => 'active'); $this->paginate['limit'] = $this->articles_per_page; // or as per your example $articles = $this->Article->find('all', array( // extra condition to check for tag, maybe? 'conditions' => array('Article.status' => 'active',$this->Article->getArticleByTagSql($tag_name)), 'limit' => $this->articles_per_page, 'offset' => ($page_num-1)*$this->articles_per_page ));