<?php
$term_names = ['Bat', 'Bi'];
$node_terms = [];
foreach ($term_names as $name) {
$tids = \Drupal::entityQuery('taxonomy_term')->condition('vid', 'vocabulary_id')->condition('name', $name)->execute();
if(!$tids) {
$term = \Drupal\taxonomy\Entity\Term::create([
'vid' => 'vocabulary_id',
'name' => $name,
]);
$term->save();
$node_terms[] = ['target_id' => $term->id()];
} else {
$node_terms[] = ['target_id' => array_shift($tids)];
}
}
$node->field_field_name->setValue($node_terms);
?>
Tags
Arloa