プログラムで語彙用語を削除する方法は?


9

語彙からすべての用語を削除したいが、語彙自体は削除したくない。

データベースでそれを行うことができますが、D8で利用可能な場合はむしろAPIを使用します。

$existingTerms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('mycustomvocab');
foreach ($existingTerms as $existingTerm) {
  // Delete vocabulary term *** This function is not available in D8 ***
  taxonomy_term_delete($existingTerm->tid);

  // Delete vocabulary - *** Not what is required ***
  /*
  $vocab = Vocabulary::load($existingTerm->vid);
  if (!is_null($vocab)) {
    $vocab->delete();
  }
  */
}

これは、私がより良い解決策を見つけるまで、現時点でそれをやっている方法です

db_query("DELETE FROM {taxonomy_term_hierarchy} WHERE `tid` IN (SELECT tid FROM {taxonomy_term_data} WHERE `vid` = :ctype)", array(':ctype' => 'mycustomvocab'));  
db_query("DELETE FROM {taxonomy_term_field_data} WHERE `vid` = :ctype", array(':ctype' => 'mycustomvocab'));
db_query("DELETE FROM {taxonomy_term_data} WHERE `vid` = :ctype", array(':ctype' => 'mycustomvocab'));

回答:


18
  $tids = \Drupal::entityQuery('taxonomy_term')
    ->condition('vid', 'mycustomvocab')
    ->execute();

  $controller = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
  $entities = $controller->loadMultiple($tids);
  $controller->delete($entities);

1

* Drupal Shellにアクセスできる場合は、次のコマンドを実行します。 drupal shell

*次に、以下をコピーして貼り付けます

function truncate_vocab($vid){
    $tids = \Drupal::entityQuery("taxonomy_term")->condition("vid",$vid)->execute();
    $controller = \Drupal::entityManager()->getStorage('taxonomy_term');
    $entites = $controller->loadMultiple($tids);
    $controller->delete($entites);
}
$vocabs = taxonomy_vocabulary_get_names();
foreach($vocabs as $vid){
   truncate_vocab($vid);
}

将来的にはDrupal Shellコマンドにするつもりです。


1

分類用語を個別に削除する別のアプローチに注意してください。いくつかの場合に役立ちます。

// Example to load and delete a taxonomy term
$tid = 12;
if ($term = \Drupal\taxonomy\Entity\Term::load($tid)) {
  // Delete the term itself
  $term->delete();
}
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.