I want to add new taxonomy term to group of nodes that have specific terms already.
To retrive them I use this function
function getNodesByTaxonomyTermIds($termIds){
$termIds = (array) $termIds;
if(empty($termIds)){
return NULL;
}
$query = \Drupal::database()->select('taxonomy_index', 'ti');
$query->fields('ti', array('nid'));
$query->condition('ti.tid', $termIds, 'IN');
$query->distinct(TRUE);
$result = $query->execute();
if($nodeIds = $result->fetchCol()){
return Node::loadMultiple($nodeIds);
}
return NULL;
}
then in foreach loop I'm adding im adding them to new term based on their creation date but adding does not work.
Here is my field structure:
Firstly I tried all of those:
$node->set('field_news_categories', ['target_id' => $termID])
$node->set('field_news_categories', $termID)
$node->set('field_news_categories', array($termID))
$node->field_news_categories->setValue(['target_id' => $termID])
$node->field_news_categories->setValue($termID)
$node->field_news_categories->setValue(array($termID))
none worked so I thought maybe I should pass whole field with exact same structure, so I wanted to get field and just append the id and then pass it as argument in set method, but I wasn't able to get field either. All I was receving were null values or empty arrays.
I tried:
$node->field_news_categories->getValue()
$node->get('field_news_categories')->getValue()
$node->field_news_categories->value
$node->get('field_news_categories')->value
$node->field_news_categories
$node->get('field_news_categories')
$node->get('field_news_categories')->target_id
$node->get('field_news_categories')->entity
$node->get('field_news_categories')->referencedEntities()
Project is in drupal 9