【发布时间】:2014-07-27 17:47:00
【问题描述】:
我需要一些帮助。我的数据库中有一个名为 posts 的表,我想在其中创建搜索引擎功能。以下是它的基本字段:
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)。我该如何解决这个问题?
EDIT正确的查询是这样的:
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
如何将其转换为活动记录??
【问题讨论】:
-
您可能会遇到 AND/OR 逻辑的 b/c 问题,添加一些括号可能会有所帮助
-
如果您处于起步阶段,我建议您使用 ORM,如 redbean 或教义。我没有在您的代码中看到 $this->db->where('visible',false) ???
-
@Dan 你是对的!这与您之前编写的查询类似。如何将其转换为 CodeIgniter 中的活动记录?我更新了我的帖子,请查看。
-
已经有一段时间了,但您可能想尝试在每个
or_like之后添加一个->where('visible',1)。 -
我取消了我的答案...并添加了一些链接以转换为活动记录。
标签: php mysql codeigniter search search-engine