如何调整searchByCategoryByName函数 使草稿状态分类下的商品不进入搜索结果
搜索结果排除草稿状态分类下商品的调整方案
核心逻辑排查
现有代码虽然在分类查询语句中写了AND status in ('publish')的过滤规则,但仍会出现草稿分类下的商品,通常是逻辑拼接漏洞、过滤条件不严谨导致的:- 硬编码的status过滤条件没有和其他拼接逻辑解耦,当排程条件拼接出现语法错位时,status校验可能被跳过
- 仅判断状态在publish列表中,未显式排除draft状态,遇到数据库隐式类型转换、字段值大小写不一致的场景,可能出现过滤失效
- 商品搜索主流程未复用该函数的分类过滤规则,独立通过分类ID关联召回了草稿分类下的商品
具体代码调整步骤
- 解耦WHERE条件拼接逻辑,避免硬编码条件被意外跳过
把原本分散拼接的WHERE子句统一归集,强制把分类状态过滤条件作为独立分支追加,不受其他排程开关影响,调整后的完整函数代码如下:public static function searchByCategoryByName($merchant_id='',$category_name='') { $db = new DbExt(); if($merchant_id > 0 && !empty($category_name)){ $where = "merchant_id = " . FunctionsV3::q($merchant_id); $todays_day = date("l"); $todays_day = !empty($todays_day)?strtolower($todays_day):''; $enabled_category_sked = getOption($merchant_id,'enabled_category_sked'); if($enabled_category_sked==1){ $where .= " AND $todays_day='1' "; } // 强化状态过滤:明确只保留已发布分类,显式排除草稿状态 $where .= " AND status = 'publish'"; $where .= " AND status != 'draft'"; $where .= " AND ( category_name like ".FunctionsV3::q( "%$category_name%" )." OR category_description LIKE ".FunctionsV3::q( "%$category_name%" )." )"; $stmt=" SELECT cat_id, merchant_id, category_name, category_description, photo, status, category_name_trans, category_description_trans FROM {{category}} WHERE $where ORDER BY category_name ASC "; if($res = $db->rst($stmt)){ return $res; } } return false; } - 对齐上下游搜索逻辑
如果商品搜索流程是独立查询商品表、再关联分类表的,需要在商品搜索的关联查询中同样追加分类状态过滤条件:AND category.status = 'publish' AND category.status != 'draft',避免分类查询过滤了草稿分类,但商品查询因为关联逻辑漏洞直接带出了草稿分类下的商品。 - 验证字段值一致性
可在数据库中查询category表的status字段实际存储值,确认publish、draft的存储大小写、格式和代码中判断的完全一致,避免因为值不匹配导致的过滤失效。
- 解耦WHERE条件拼接逻辑,避免硬编码条件被意外跳过
内容的提问来源于stack exchange,提问作者Efendi Efendiyev
相关产品推荐
相关产品推荐

