PrestaShop 1.7.8 API创建简单商品时生成空product_attribute记录的Bug
解决PrestaShop API创建简单商品时生成空product_attribute记录的问题
针对你遇到的API创建无组合简单商品时,PrestaShop自动生成空product_attribute记录的问题,在不升级核心的前提下,可以通过以下两种方案修复:
方案一:修改核心Product类(直接高效)
找到classes/Product.php中的add()方法,在商品成功保存到数据库的逻辑之后,添加一段清理空属性记录的代码:
// 商品保存完成后追加以下代码 if (!$this->hasCombinations()) { // 删除当前商品对应的空属性记录 Db::getInstance()->delete( 'product_attribute', 'id_product = '.(int)$this->id.' AND id_attribute_group = 0 AND id_attribute = 0' ); }
这段代码会在商品创建后检查是否存在组合,若为无组合的简单商品,则删除自动生成的空product_attribute条目。
方案二:通过WebService钩子拦截(无核心修改,更安全)
如果不想修改核心文件,可以创建一个自定义模块,利用PrestaShop的钩子在API创建商品后执行清理操作:
- 创建新模块,在主模块文件中注册
actionObjectProductAddAfter钩子:
class FixEmptyProductAttribute extends Module { public function __construct() { $this->name = 'fixemptyproductattribute'; $this->tab = 'administration'; $this->version = '1.0.0'; $this->author = 'Your Name'; $this->need_instance = 0; parent::__construct(); $this->displayName = $this->l('Fix Empty Product Attribute'); $this->description = $this->l('Removes empty product_attribute records created when adding simple products via API'); } public function install() { return parent::install() && $this->registerHook('actionObjectProductAddAfter'); } public function hookActionObjectProductAddAfter($params) { $product = $params['object']; if (!$product->hasCombinations()) { Db::getInstance()->execute(' DELETE FROM '._DB_PREFIX_.'product_attribute WHERE id_product = '.(int)$product->id.' AND id_attribute_group = 0 AND id_attribute = 0 '); } } }
- 将模块上传到
modules/目录,在后台安装启用即可。
注意事项
- 所有操作先在开发环境测试,确认不会误删有效组合记录;
- 升级PrestaShop到修复该问题的版本后,记得移除自定义代码或模块;
- 若你的PrestaShop版本中自动生成的空记录字段条件不同,可以调整SQL查询的WHERE条件匹配实际数据。
内容的提问来源于stack exchange,提问作者leodedro
相关产品推荐
相关产品推荐

