0

product import csv containing category data which is given as below

Default Category/Diagrams/Business,Default Category/Diagrams/Strategy,Default Category/Diagrams/Planning,Default Category/Diagrams/Marketing,Default Category/Diagrams/Icons

I want to fetch category ids from the above string.

2 Answers 2

0

please check in

/var/www/html/magento231/vendor/magento/module-catalog-import-export/Model/Import/Product.php

find _saveProducts() method:

in while ($bunch = $this->_dataSourceModel->getNextBunch())

you will ($bunch) get data bunchwise

get category title from it and apply below soultion in it:

Magento 2 Get category id using category title

0

I would have said something more like this. Want to explode string.


$strings = explode("/", "Default Category/Diagrams/Business,Default Category/Diagrams/Strategy,Default Category/Diagrams/Planning,Default Category/Diagrams/Marketing,Default Category/Diagrams/Icons");

$categoryIds = [];
foreach($strings as $string) {
    if($id = $this->getCategoryTitleFromId($string)) {
        $categoryIds[] = $id;
    }
}

Your method to load ID by string will look like this

public function __construct(
    \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $collectionFactory 
) {
    $this->collectionFactory = $collectionFactory ;
}

public function getCategoryTitleFromId($title) {
    $collection = $this->collectionFactory 
        ->create()
        ->addAttributeToFilter('name', $title)
        ->setPageSize(1);

    if ($collection->getSize()) {
        return $collection->getFirstItem()->getId();
    }
    return null;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.