Magento – Mass delete action in one step not in loop magento 2

magento2massaction

I have custom module with mass delete action feature. how to do mass delete action in one step without loop. Because i got WARNING | Model LSD method delete() detected in loop when i check my module in MEQP 2.

Below is the code used in my module

foreach ($collection as $block) 
{

 $block->delete();

}

After searching the mass action in the MAGE2 core file they too use the same method.
i refered the following path file is vendor/magento/module-cms/Controller/Adminhtml/Block/MassDelete.php

from line no 51 to 53

foreach ($collection as $page) 
{
    $page->delete();
}

i appreciate any one help on this.

Best Answer

try {
    $categoriesIds = ['1','2','3'];
    // use collection factory object of particular model
    $catgoryObj = $this->_objectManager->get('MageArray\Gallery\Model\ResourceModel\Category\CollectionFactory');

    //apply addFieldToFilter  to get particular  record only  from that collection
    $category = $catgoryObj->create()->addFieldToFilter('category_id', array('in' => $categoriesIds));

    //use walk method for mass delete action
    $category->walk('delete'); 
    $this->messageManager->addSuccess(__('A total of %1 record(s) have been deleted.', count($categoriesIds)));

} catch (\Exception $e) {
    $this->messageManager->addError($e->getMessage());
}
Related Topic