Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all items in a magento product collection?

Seems doesn't works:

<?php
    $collection = Mage::getModel('catalog/product')->getCollection();
    foreach($collection->getItems() as $key => $_product){
        //product
        $collection->removeItemByKey($key);
    }

?>

$collection is still populated

like image 459
Antonino Bonumore Avatar asked Dec 10 '11 00:12

Antonino Bonumore


People also ask

How do I bulk delete items in Magento?

You can delete products from Magento 2 in bulk by using the same process as Bulk Update but by unchecking “Web” while updating products. This will delete the products from Magento 2 during the next sync.

How do I remove all items from magento2?

Re: Deleting ALL products from Magento 2 you can delete from the database as well using following query. delete from catalog_product_entity; But It will delete all the products from the magento. If you want to delete specific products then you can use where condition as well.

Can Magento handle millions of products?

Magento 2 can easily handle more than 1 million products.


2 Answers

There's also a possibility to remove all the items without "fake loading" (in opposite to Shay Acrich's answer):

class MyCollection extends SomeCollection {

    // ...

    public function setEmpty()
    {
        $this->clear();
        $this->_totalRecords = 0;
        $this->_setIsLoaded(true);
        return $this;
    }

    // ...

}

Setting _totalRecords to 0 is required in order not to allow getSize() method to reload the collection.

Nevertheless, one needs to extend / modify a collection's code, because both the field _totalRecords and the method _setIsLoaded() are protected.

There should be noted, that if a particular collection ignores flags like _totalRecords and _isCollectionLoaded the above solution may not work as expected.

like image 139
jacek.ciach Avatar answered Nov 10 '22 01:11

jacek.ciach


There's clear() method in Varien_Data_Collection class which clears the collection.

I'm not sure if the method exists in the time the question was asked, but it exists in Magento 1.7

like image 36
Anatoly A. Kazantsev Avatar answered Nov 10 '22 01:11

Anatoly A. Kazantsev