尝试创建搜索功能,取决于复选框,它可以找到文章的标题,文字和标签
这是我的功能,但是它对DB使用了几个请求,而我正在尝试使用一个请求;)
public function search_articles($title=NULL, $tag=NULL, $text=NULL)
{
$articles = array();
if ($tag !== NULL) {
$this->db->select('articles.*')
->from('articles')
->from('tags')
->from('articles_tags_rel')
->where('articles.id = articles_tags_rel. article_id')
->where('articles_tags_rel.tag_id = tags.id')
->where('tags.name', $tag);
$articles = array_merge($articles, $this->db->get()->result_array());
}
if ($text !== NULL) {
$this->db->select('*')
->from('articles')
->like('text', $text)
->order_by('title');
$articles = array_merge($articles, $this->db->get()->result_array());
}
if ($title !== NULL) {
$this->db->select('*')
->from('articles')
->like('title', $title)
->order_by('title');
$articles = array_merge($articles, $this->db->get()->result_array());
}
$articles = unique_multidim_array($articles, 'id'); // TODO: better to get unique using mysql then php?
return $articles;
}
我在DB中有3个表:文章 - id,text; tags - id,name; articles_tag_rel - article_id,tag_id
如何更好地检查用户点击的复选框以及如何构建查询以获取带有w / 1请求的文章?
泰
UPD:自己做了:)这里是新版本:
/**
* Search articles by text/title/tags depends on checkboxes values
* @param array $data of checkboxes values, keys can be 'tag'/'title'/'text'
* @return array $articles of non-repeat articles
*/
public function search_articles($data)
{
$str = "";
if (isset($data['tag'])) {
$this->db
->select('articles.*')
->from('articles')
->from('tags')
->from('articles_tags_rel')
->where('articles.id = articles_tags_rel. article_id')
->where('articles_tags_rel.tag_id = tags.id')
->where('tags.name', $data['tag']);
$str = $this->db->get_compiled_select();
unset($data['tag']);
}
foreach ($data as $key => $value) {
$this->db
->select('*')->from('articles')
->like($key, $value);
$str .= (!$str) ? $this->db->get_compiled_select() : " UNION ". $this->db->get_compiled_select();
}
$articles = $this->db->query($str)->result_array();
return $articles;
}