我想请一些帮助。我在我的数据库中有一个名为posts的表,我希望创建一个搜索引擎功能。下面是该基本字段:CodeIgniter搜索引擎不能正常工作 - 只能发布文章
table: Posts
post_id (pk)
title
keywords
visible // **** this is the critical point ****
我创建也是这个方法我post_model:
public function search() {
$this->db->select('post_id, title, etc etc ...');
// separate the words
$words = preg_split('/[\s]+/', htmlentities((trim($this->input->post('search'))))) ;
// set fields that you wish to search
$search_fields = array('title', 'keywords');
// build the query
foreach ($words as $word) {
foreach ($search_fields as $field) {
$this->db->or_like($field, $word);
}
}
return parent::get();
}
// Generates this query:
SELECT `post_id`, `title` etc etc ...
FROM (`posts`)
WHERE `posts`.`date_published` <= '2014-06-06'
AND `posts`.`visible` = 1
AND `title` LIKE '%Lorem,%'
OR `keywords` LIKE '%Lorem,%'
OR `title` LIKE '%Ipsum%'
OR `keywords` LIKE '%Ipsum%'
ORDER BY `date_published` DESC, `posts`.`category_id` ASC, `post_id` DESC
// This is the get() function inside MY_Model
// Returns results like this $this->db->get($this->_table_name)->result();
public function get($id = NULL, $single = FALSE){
if ($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
}
elseif($single == TRUE) {
$method = 'row';
}
else {
$method = 'result';
}
if (!count($this->db->ar_orderby)) {
$this->db->order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
的问题是,我也得和未发表的帖子(可见= 0)这一点,这不是预期的,而是我想得到的仅仅是发布的帖子(可见= 1)。我怎样才能解决这个问题 ?
编辑正确的查询是这样的:
SELECT `post_id`, `title` ... . *
FROM (`posts`)
WHERE `date_published` <= '2014-06-06'
AND `visible` =1
AND (
`title` LIKE '%Lorem,%'
OR `keywords` LIKE '%Lorem,%'
OR `title` LIKE '%Ipsum%'
OR `keywords` LIKE '%Ipsum%'
)
ORDER BY `date_published` DESC , `posts`.`category_id` ASC , `post_id` DESC
我怎样才能将它转换为一个有效记录?
你可能会遇到的问题B/C与/或逻辑的,加入一些括号可以帮助 – Dan
如果你在开始的道路上,我建议你使用ORM,像redbean或doctrine。我没有在代码中看到$ this-> db-> where('visible',false)? – merdan
@丹你说得对!这与你所写的查询类似。我怎样才能将其转换为CodeIgniter中的活动记录?我对我的文章做了更新,请回顾。 – Lykos