5

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.

3
  • instead of iterating and deleting on object, use custom My Sql query to delete multiple row with where cause. Jun 29, 2017 at 10:48
  • delete on object is only useful when you want to perform other operation before deleting it. Jun 29, 2017 at 10:51
  • @Jjo did you find an answer to this? Thanks
    – Tom Burman
    Aug 2, 2017 at 6:23

2 Answers 2

3

Took me a little while to get syntax right on this but you can do a delete from select

Not saying it fits your project but I think it is useful to know

https://github.com/DominicWatts/QuoteCleaner/blob/master/Helper/Cleaner.php

    /**
     * @param \Magento\Framework\App\Helper\Context $context
     * @param \Psr\Log\LoggerInterface $logger
     */
    public function __construct(
        \Magento\Framework\App\ResourceConnection $resource
    ) {
        $this->connection = $resource->getConnection();
        $this->resource = $resource;
    }

    $select = $this->connection
        ->select()
        ->from($this->tableName)
        ->where('ISNULL(customer_id) OR customer_id = 0')
        ->where('updated_at < DATE_SUB(NOW(), INTERVAL ? DAY)', 31)
        ->limit(1000);

    $query = $this->connection->deleteFromSelect($select, []);
    $statement = $this->connection->query($query);
2
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());
}

Your Answer

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

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