Prestashop为产品添加多分类保存后仅保留id_category_default问题求助
Prestashop 产品多分类绑定仅默认分类生效问题解决
问题复现
基于Prestashop做二次开发时,通过代码给产品绑定多个分类,保存后仅id_category_default指定的默认分类关联成功,其余配置的分类均未绑定。
原实现代码:
$xml = simplexml_load_file('php://input'); $product = new Product($xml->id); $product->category = [2,7]; $product->id_category_default = (int)$xml->id_category_default; //categories $product->name = $xml->name; //nom produit $product->price = $xml->price; //prix $product->id_tax_rules_group = (int)$xml->id_tax_rules_group; $product->ean13 = $xml->ean13; //code barre $product->description = $xml->description; //description $product->description_short = $xml->description_short; //petite description $product->reference = $xml->reference; //reference $product->weight = $xml->weight; //poids $product->height = $xml->height; //hauteur $product->width = $xml->width; //largeur $product->depth = $xml->depth; //profondeur $product->indexed = 1; $product->active = true; $product->save(); $e = $product->getDefaultIdProductAttribute(); StockAvailable::setQuantity($product->id, $e, $xml->quantity); $image = new Image(); $image->id_product = $product->id; $image->position = Image::getHighestPosition($product->id) + 1; $image->cover = true; $image->add(); AdminImportControllerCore::copyImg((int)$product->id, (int)$image->id, $xml->urlImage, 'products', false);
运行后实际效果:
根因说明
Prestashop Product 类用于接收多分类ID的属性名是id_category,不是category。原代码给不存在的category属性赋值,核心保存逻辑读取不到多分类列表,自然不会写入分类关联表,最终只有默认分类被关联。
修复步骤
- 将多分类赋值操作的属性改为
$product->id_category - 分类ID数组必须包含
id_category_default对应的默认分类ID,否则会出现默认分类关联异常 - 数组内所有分类ID统一转为整型,避免类型校验失败导致写入被过滤
修复后完整代码
$xml = simplexml_load_file('php://input'); $product = new Product($xml->id); // 先提取默认分类ID $defaultCategoryId = (int)$xml->id_category_default; // 正确赋值多分类,必须包含默认分类 $product->id_category = [ $defaultCategoryId, 2, 7 ]; $product->id_category_default = $defaultCategoryId; $product->name = $xml->name; $product->price = $xml->price; $product->id_tax_rules_group = (int)$xml->id_tax_rules_group; $product->ean13 = $xml->ean13; $product->description = $xml->description; $product->description_short = $xml->description_short; $product->reference = $xml->reference; $product->weight = $xml->weight; $product->height = $xml->height; $product->width = $xml->width; $product->depth = $xml->depth; $product->indexed = 1; $product->active = true; $product->save(); $e = $product->getDefaultIdProductAttribute(); StockAvailable::setQuantity($product->id, $e, $xml->quantity); $image = new Image(); $image->id_product = $product->id; $image->position = Image::getHighestPosition($product->id) + 1; $image->cover = true; $image->add(); AdminImportControllerCore::copyImg((int)$product->id, (int)$image->id, $xml->urlImage, 'products', false);
补充:如果是更新已有产品的分类,需要清空之前绑定的旧分类,可以在给
$product->id_category赋值前执行$product->deleteCategories();,再保存即可覆盖旧的关联关系。
内容的提问来源于stack exchange,提问作者Baptiste L
相关产品推荐
相关产品推荐

