cancel
Showing results for 
Search instead for 
Did you mean: 

Remove All Products Related to Specific Store Id

Remove All Products Related to Specific Store Id

Hi,

 

I have coded a script to import my products. 

It seems that - during coding and testing - many products have been created and connected to two different store IDs (0 and 1).

 

See here the details from one product in the database:

MariaDB [magentodb]> SELECT * FROM catalog_product_entity c1, catalog_product_entity_int c2 WHERE c1.sku = 70048 AND c2.entity_id = c1.entity_id AND c2.attribute_id = 97\G 
*************************** 1. row ***************************
entity_id: 5637
attribute_set_id: 9
type_id: simple
sku: 70048
has_options: 0
required_options: 0
created_at: 2021-04-09 00:09:11
updated_at: 2021-07-14 11:43:37
value_id: 63089
attribute_id: 97
store_id: 0
entity_id: 5637
value: 0
*************************** 2. row ***************************
entity_id: 5637
attribute_set_id: 9
type_id: simple
sku: 70048
has_options: 0
required_options: 0
created_at: 2021-04-09 00:09:11
updated_at: 2021-07-14 11:43:37
value_id: 495803
attribute_id: 97
store_id: 1
entity_id: 5637
value: 1

The value at the end shows that one version is active and the other is not.

The version I see in my admin is the first one. The version that is shown in the front-end is the second.

 

My question is:

How can I remove all the products related to the store-id = 0 so that I keep those with store-id = 1?

 

Thanks for you help

2 REPLIES 2

Re: Remove All Products Related to Specific Store Id

First I would like to suggest you try to avoid object manager directly in your code.

<?php
namespace VendorName\ModuleName\Block;
class Product extends \Magento\Framework\View\Element\Template
{    
    public $productCollectionFactory;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,        
        array $data = []
    )
    {    
        $this->productCollectionFactory = $productCollectionFactory;    
        parent::__construct($context, $data);
    }

    public function getProductCollection()
    {
        $storeId = 0; 
        $collection = $this->productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->addStoreFilter($storeId);        
        return $collection;
    }
}
?>

Now you have product collection where store_id = 0. By using foreach loop through collection delete the products.

Click Kudos and Accept it as a solution its encourages me to write more answers.

 

Re: Remove All Products Related to Specific Store Id

I have also same error any one have solution for this?

 

MyAARPMedicare