Drupal 8:删除相同类型的所有节点

问题描述 投票:0回答:10

我需要删除 Drupal 8 中相同类型的所有节点(有超过 7k 个节点)。

对于 Drupal 7 来说这不是问题(数据库查询+node_delete或node_delete_multiple可以解决我的问题)。然而,D8 略有不同:)

请指教,我该怎么做。预先感谢!

drupal-8
10个回答
25
投票

应该使用实体查询而不是直接作用于数据库:

  $result = \Drupal::entityQuery('node')
      ->condition('type', 'my_content_type_name')
      ->execute();
  entity_delete_multiple('node', $result);

像其他答案一样设置范围应该不会太困难。

请参阅EntityFieldQuery 已被重写以获取更多信息。


12
投票

entity_delete_multiple 从 Drupal 8.0.x 开始已弃用,将在 Drupal 9.0.0 之前删除。使用实体存储的delete()方法删除多个实体:

// query all entities you want for example taxonomy term from tags vocabulary
$query = \Drupal::entityQuery('taxonomy_term');
$query->condition('vid', 'tags');
$tids = $query->execute();

$storage_handler = \Drupal::entityTypeManager()->getStorage($entity_type);
$entities = $storage_handler->loadMultiple($tids);
$storage_handler->delete($entities);

11
投票

您可以使用开发模块

  1. 进入管理->配置->开发->生成内容
    (管理/配置/开发/生成/内容)
  2. 选择您想要删除其节点的内容类型。
  3. 选中“删除这些内容类型中的所有内容..”(重要)
  4. 在“你想生成多少个节点”中输入“0”(重要)

请参阅附图了解说明。

attached image


8
投票

嗯,答案就在表面上:

$types = array('my_content_type_name');

$nids_query = db_select('node', 'n')
->fields('n', array('nid'))
->condition('n.type', $types, 'IN')
->range(0, 500)
->execute();

$nids = $nids_query->fetchCol();

entity_delete_multiple('node', $nids);

我建议您使用“范围”和某种“批处理”(或者只是多次重新运行代码),因为这是一个非常胖的操作(每个操作 500 个节点对于 256MB 来说是可以的)。

要执行此代码,您可以编写自定义模块或使用 devel 模块:https://www.drupal.org/project/devel

安装后,转到 yoursite_address/devel/php 并在那里执行 php 代码。


8
投票

Drupal 8 具有按内容类型获取节点的功能,所以我会使用

$nodes = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->loadByProperties(array('type' => 'your_content_type'));

foreach ($nodes as $node) {
    $node->delete();
}

3
投票

非常简单的方法是安装批量删除模块。适用于 D7 和 D8。

安装模块后,单击内容菜单时,您将看到批量删除节点选项卡选项。

它拯救了我的一天:)

为了您的方便,我附上了屏幕截图。


1
投票

要删除某些实体类型的所有实体,我使用根据上次评论改编的代码片段:

$entity_types = ['taxonomy_term','node','menu_link_content',];
foreach ($entity_types as $entity_type) {
  $query = \Drupal::entityQuery($entity_type);
  $ids = $query->execute();

  $storage_handler = \Drupal::entityTypeManager()->getStorage($entity_type);
  $entities = $storage_handler->loadMultiple($ids);
  $storage_handler->delete($entities);
}

1
投票

我为此使用 Drupal 控制台 https://docs.drupalconsole.com/ko/commands/entity-delete.html

drupal entity:delete [arguments]


0
投票

Drupal 9.0 工作正常

  $ids = \Drupal::entityQuery('node')
    ->condition('type', 'article')
    ->execute();

  $storage_handler = \Drupal::entityTypeManager()->getStorage("node");
  $entities = $storage_handler->loadMultiple($ids);
  $storage_handler->delete($entities);

0
投票

如果您只能访问API,并且所有要删除的节点ID都在给定的值范围内(例如,它们是批量插入的),您可以这样做:

printf "%s\0" {3000..4000} | xargs -0 -I @ -P 7  curl --include --request DELETE --user your_api_user:'your_api_user_password' --header 'X-CSRF-Token: your_api_key' "http://your_website/node/@?_format=hal_json"

这将删除使用 7 个 CPU 核心 (-P 7) 的节点 3000 到 4000。

© www.soinside.com 2019 - 2024. All rights reserved.