0

I am trying to unassign a category from a product. This category has a large number of products assigned to it (like 1500+). I used the code

`$CategoryLinkRepository ->deleteByIds($categoryId, $productSku);`

but this function essentially is un-tagging all this single product from category's assigned product list and saving the category. Which in turn is resulting in a lot of big queries (like real big queries which you won't want to see getting fired at your database) being fired at MySQL and getting timed out? A code snippet is as follows:

    public function deleteByIds($categoryId, $sku)
    {
        $category = $this->categoryRepository->get($categoryId);
        $product = $this->productRepository->get($sku);
        $productPositions = $category->getProductsPosition();

        $productID = $product->getId();
        if (!isset($productPositions[$productID])) {
            throw new InputException(__('Category does not contain specified product'));
        }
        $backupPosition = $productPositions[$productID];
        unset($productPositions[$productID]);

        $category->setPostedProducts($productPositions);
        try {
            $category->save();
        } catch (\Exception $e) {
            throw new CouldNotSaveException(
                __(
                    'Could not save product "%product" with position %position to category %category',
                    [
                        "product" => $product->getId(),
                        "position" => $backupPosition,
                        "category" => $category->getId()
                    ]
                ),
                $e
            );
        }
        return true;
    }
  • If I use a query like delete from catalog_category_product where category_id = 4 and product_id = 46;. Should this work safely? I understand that there could be some garbage data left like urls etc. – Gaurav Pandey Apr 21 at 17:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.