Question

I have created Data Patch, debugged it and everything works as expected, products are removed from the collection but after running setup upgrade changes are not made in the database, what can be cause of the error ? My code is below

<?php

declare(strict_types=1);

namespace DevAll\ExtensionSettingConfig\Setup\Patch\Data;

use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\StateException;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Api\AttributeRepositoryInterface;
use Magento\Catalog\Model\ProductRepositoryIn;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\Area;
use Magento\Framework\App\State;
class RemoveLGManufacturer implements DataPatchInterface
{
    private $eavSetupFactory;

    private $attributeRepository;

    private $_productRepositoryInterface;

    private $collectionFactory;

    private $state;

    private  $productCollectionFactory;

    private $productRepository;

    private $searchCriteriaBuilder;
    public function __construct(
        State $state,
        CollectionFactory $collectionFactory,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        AttributeRepositoryInterface $attributeRepository,
        ProductRepositoryInterface $productRepositoryInterface,
        array $data = []
    ) {
        $this->state = $state;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->_productRepositoryInterface = $productRepositoryInterface;
        $this->attributeRepository = $attributeRepository;
        $this->collectionFactory = $collectionFactory;
    }

    /**
     * @inheritDoc
     */
    public static function getDependencies()
    {
        return [];
    }

    /**
     * @inheritDoc
     */
    public function getAliases()
    {
        return [];
    }
    public function apply()
    {
          //$searchCriteria = $this->searchCriteriaBuilder->addFilter('manufacturer','LG')->create();



        $productcollection = $this->collectionFactory->create()->addAttributeToSelect('manufacturer','LG')->load();
        foreach ($productcollection as $product) {
            try {
                $productcollection->removeItemByKey($product->getId());
            } catch (StateException $e) {
            }
        }
        return $productcollection;
    }

}
Was it helpful?

Solution

removeItemByKey does not delete a product from the database. It just removes it from the product collection object.
If you want to remove products you can use

$this->_productRepositoryInterface->delete($product);
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top