0

I'm deleting multiple nodes like this:

$nids = [21,12,45,67]; // Just an example, this data comes from elsewhere
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);
\Drupal::entityTypeManager()->getStorage('node')->delete($nodes);

Drupal is running out of memory when deleting just 6 nodes.

I'm having this problem in general, not just when deleting, but any time I work with multiple nodes. The PHP memory_limit is 256MB and the server admin is reluctant to increase this. Even if it is increased, it's just postponing the problem - it might fail on 12 or 16 instead of 6.

Is there another way, e.g. to delete based on nid without loading the full node object and all of its fields? The deprecated entity_delete_multiple appears to load the entities before deleting anyway. I suspect it has to because various hooks have to be called and it has to delete revisions and field data.

Or is there some special way I can code it to delete one node at a time and free each object afterwards to keep memory usage low?

  • 2
    Great that the answer worked, but running out of memory with just 6 nodes is really strange, especially since you can delete 600 of them when loading one by one without any major memory leaks apparently. It might be worth to use blackfire.io, a similar profiling too or just plain php memory usage functions and figure out what is happening.. could be a hook doing something strange or so. – Berdir Apr 20 '17 at 23:04
6

Loading/deleting one at a time may use less memory:

use Drupal\node\Entity\Node;

$nids = [21,12,45,67];
foreach($nids as $nid)
{
  $node = Node::load($nid);
  $node->delete();
}

Each loop will overwrite the previous instance of $node, releasing the memory.

| improve this answer | |
  • It works perfectly, didn't run out of memory when deleting 600 nodes. I will just have to avoid loadMultiple() in my code to avoid this problem in future. – Rob Apr 20 '17 at 14:16
  • Glad it worked! – Jaypan Apr 20 '17 at 14:17
4

You could also chunk the array of ids into smaller chunks in order to use less memory and avoid looping once for every single node:

$nids = [
   // Some big list of nids...
];
$storage = \Drupal::entityTypeManager()->getStorage('node');
foreach (array_chunk($nids, 50) as $chunk) {
  $nodes = $storage->loadMultiple($chunk);
  $storage->delete($nodes); 
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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