Infinite(Codingest 开发)基于 CodeIgniter 框架构建,默认的搜索逻辑使用的是 MySQL 的原生 LIKE '%关键词%' 查询。
中文搜索失效(必须全匹配)的核心原因在于:MySQL 数据库对中文(CJK 字符)没有进行分词索引,且前端或后端在接收搜索参数时,可能进行了不恰当的转义或没有使用通配符包裹。
打开 app/Models/PostModel.php 文件,找到下面的代码
public function getSearchPostsPaginated($langId, $q, $perPage, $offset)
{
$this->buildQuery($langId);
return $this->builder->where("MATCH(title, summary, content) AGAINST({$this->db->escape($q)} IN NATURAL LANGUAGE MODE)")->limit(clrNum($perPage) + 1, clrNum($offset))->get()->getResult();
}
替换成
// 修改后的搜索方法(改为经典 LIKE 模糊匹配,支持中文任意断句与片段搜索)
public function getSearchPostsPaginated($langId, $q, $perPage, $offset)
{
$this->buildQuery($langId);
// 拆分多关键词(支持空格分隔多词搜索)
$keywords = explode(' ', preg_replace('/\s+/', ' ', trim($q)));
$this->builder->groupStart();
foreach ($keywords as $index => $word) {
if (!empty($word)) {
$escapedWord = $this->db->escapeLikeString($word);
if ($index === 0) {
$this->builder->groupStart()
->like('posts.title', $escapedWord)
->orLike('posts.summary', $escapedWord)
->orLike('posts.content', $escapedWord)
->groupEnd();
} else {
$this->builder->orGroupStart()
->like('posts.title', $escapedWord)
->orLike('posts.summary', $escapedWord)
->orLike('posts.content', $escapedWord)
->groupEnd();
}
}
}
$this->builder->groupEnd();
return $this->builder->orderBy('posts.id', 'DESC')
->limit(clrNum($perPage) + 1, clrNum($offset))
->get()
->getResult();
}
保存上传,尝试搜索,即可实现 中文局部匹配 和 多词模糊 搜索了!