本文介紹了帶有“hasAndBelongsToMany"控制器的 CakePHP 條件查詢的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我為這個可怕的標題道歉,我想不出如何解釋我的問題.
I apologize for the horrible title, I couldn't think of how to explain my problem.
在我的數(shù)據(jù)庫中,我有以下表格:articles
、tags
和 articles_tags
.一篇文章可以有多個標簽.
In my database I have the following tables, articles
, tags
, and articles_tags
. An article can have many tags.
目前我能夠抓取所有帶有所有標簽的文章,但我希望能夠根據(jù)它的標簽找到文章.
Currently I am able to grab all the articles, with all the tags, but I want to be able to find articles based upon it's 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
));
我從數(shù)據(jù)庫返回如下:
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
標簽的文章怎么辦?
What do I do if I only want to return the articles with a Ruby
tag?
推薦答案
試試這個
// 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
));
這篇關(guān)于帶有“hasAndBelongsToMany"控制器的 CakePHP 條件查詢的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!