在某些条件下删除实体Drupal 8

时间:2016-04-26 09:14:38

标签: entity drupal-8

任务是删除满足某些指定条件的实体。我该怎么办?

$current_user = \Drupal::currentUser()->id();
$storage = \Drupal::entityManager()->getStorage('context');

$query = $storage->getQuery()->condition('user_id', $current_user);

$query = $storage->getQuery()->delete();
$query->condition('user_id', $current_user);
$query->condition('key_text', $key);

$query->execute();

但代码返回:致命错误:调用未定义的方法Drupal \ Core \ Config \ Entity \ Query \ Query :: delete()

5 个答案:

答案 0 :(得分:2)

要查询实体,您可以使用entityQuery,下面的示例使用此。

// Get all users with email containing "xyz"
$query = \Drupal::entityQuery('user')
  ->condition('mail', "XYZ", 'CONTAINS');
$uids = $query->execute();

// Load these entities ($uids) in our case using storage controller.
// We call loadMultiple method and give $uids array as argument.     
$itemsToDelete = \Drupal::entityTypeManager()->getStorage('user')
  ->loadMultiple($uids);

// Loop through our entities and deleting them by calling by delete method.
foreach ($itemsToDelete as $item) {
  $item->delete();
}

答案 1 :(得分:1)

使用实体存储的delete()方法删除多个实体。没有必要迭代所有这些。

$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);

取自https://stackoverflow.com/a/43786945/442022

答案 2 :(得分:0)

在实际删除实体之前,您需要先获取实体。更新它们或从中获取信息也需要此方法。希望下面的代码可以帮助:)

$current_user = \Drupal::currentUser()->id();    

$ids = \Drupal::entityQuery('context')
          ->condition('user_id', $current_user)
          ->execute();

$itemsToDelete = $this->entityTypeManager->getStorage('context')
          ->loadMultiple($ids);


foreach ($itemsToDelete as $item) {
   $item->delete();
}

答案 3 :(得分:0)

错误消息是由于您用于查询配置实体的类没有delete()方法而引起的。对于内容实体也是如此。 delete()方法由实体实现,因此正确的代码类似于以下代码。

$storage = \Drupal::entityTypeManager()->getStorage('context');
$query = $storage->getQuery();

$ids = $query->condition('user_id', $current_user)
  ->condition('key_text', $key)
  ->execute();

foreach ($storage->loadMultiple($ids) as $entity) {
  $entity->delete();
}

请参阅entity.query service deprecated in favor of EntityStorageInterface::getQuery()

答案 4 :(得分:0)

我知道它已经很旧了,但是我碰到了这个问题,以为我应该发布。.
我有一个要从中删除项目的自定义实体表。.我不是100%肯定此方法的含义,但是我想它不会调用任何实体挂钩,但它会提供更高的性能。

$database = \Drupal::service('database');
$query = $database->delete('my_custom_entity_table');
$query->condition('my_field', $value_to_check_for);
$query->execute();