3

So I've been dealing with this problem for quite some time and can't find a clear solution. So basically I'm adding new products directly into db using Product object. For now it went well but I can't manage to link new products with a category.

$cat_ids = [];
    foreach ($value['kat_naziv'] as $cat_val) {
    $cat_ids[] = (int)$luceed->selectCategoryIds($cat_val)[$cat_val]['id_category'];
}

$product->id_category = 3;
$product->id_category_default = 3;

$product->save();

$product->addToCategories($cat_ids);

So basically $cat_ids is an array of integers that i'm getting from db where name is something i pass as a parameter to selectCategoryIds;

What is the problem here why it wont associate newly created product with categories i give to it

4

3 回答 3

2

创建新产品后(即 $product = new Product() )。您可以将类别分配给产品使用。

$product->updateCategories($category_array); 

在哪里

$category_array = array("0" => "2", "1" => "3", "4" => "6"...... );
于 2016-06-10T09:21:38.723 回答
0

@FMEModule That's exactly what i did there but i've filled the array with the id's of categories from the database

Anyways I ended up writing my own queries for associatting products with categories

于 2016-06-10T12:32:20.797 回答
0

版本 (1.6)

Product.php我在addToCategories搜索if (!in_array($new_id_categ, $current_categories))(第 964 行)中发现了以下错误,

请注意if缺少{}- 添加它们,问题就解决了:

    foreach ($categories as $new_id_categ) {

        if (!in_array($new_id_categ, $current_categories)) {

            if ($position == null) {
                $position = (int)$new_categ_pos[$new_id_categ];
            }
            $product_cats[] = array(
                'id_category' => (int)$new_id_categ,
                'id_product' => (int)$this->id,
                'position' => $position,
            );
        }

    }

Prestashop 开发人员喜欢在 and 之后省略-{}这非常烦人且容易出错。ifforeach

此问题已在 repo 中修复: https ://github.com/PrestaShop/PrestaShop/blob/1.6.1.x/classes/Product.php

注意:此解决方案解决了以下场景中的错误 -a product that is already link to a category is link to another category (while keeping the original category) 尽管我不确定这是否是问题中的场景。

于 2018-01-26T11:15:57.337 回答