9

I was wondering if there was a way of walking through a collection on Magento 2 and deleting entries from the database.

In Magento 1, this could be done by doing something like the following:

Mage::getModel('foo/bar')->getCollection()
                    ->addFilter('baz', $filter)
                    ->walk('delete')

Is there a way of achieving something similar in Magento 2?

2 Answers 2

28

It's the same method in M2 you can do

$collection->walk('delete');

A few examples from native Magento 2 files:

1
  • Really appreciate! Commented Jan 5, 2018 at 9:43
8

I could easily be wrong, but I think it depends on the entity with which you are working. Take a couple references from the core, e.g.:

\Magento\Eav\Model\Entity\Collection\AbstractCollection::delete()

public function delete()
{
    foreach ($this->getItems() as $key => $item) {
        $this->getEntity()->delete($item);
        unset($this->_items[$key]);
    }
    return $this;
}

\Magento\Customer\Controller\Adminhtml\Index\MassDelete::massAction():

protected function massAction(AbstractCollection $collection)
{
    $customersDeleted = 0;
    foreach ($collection->getAllIds() as $customerId) {
        $this->customerRepository->deleteById($customerId);
        $customersDeleted++;
    }
    //snip...
}

\Magento\Catalog\Controller\Adminhtml\Product\MassDelete::execute()

public function execute()
{
    $collection = $this->filter->getCollection($this->collectionFactory->create());
    $productDeleted = 0;
    foreach ($collection->getItems() as $product) {
        $product->delete();
        $productDeleted++;
    }
    $this->messageManager->addSuccess(
        __('A total of %1 record(s) have been deleted.', $productDeleted)
    );

    return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT)->setPath('catalog/*/index');
}

It comes down to whether there is a service layer setup for the entity.

2
  • It sounds about right, my answer was specific to the OP case as it seems like he/she used to do that with a custom entity back in M1 Commented Jun 2, 2016 at 20:10
  • 2
    Yep, mine evidently waited hours to post. Most likely because I forgot all about it and never actually clicked "post"
    – benmarks
    Commented Jun 2, 2016 at 20:49

Your Answer

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

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