按名称加载字词


Answers:


19

Drupal 8中似乎已弃用该功能。
请改用taxonomy_term_load_multiple_by_name函数。

<?php

  /**
   * Utility: find term by name and vid.
   * @param null $name
   *  Term name
   * @param null $vid
   *  Term vid
   * @return int
   *  Term id or 0 if none.
   */
  protected function getTidByName($name = NULL, $vid = NULL) {
    $properties = [];
    if (!empty($name)) {
      $properties['name'] = $name;
    }
    if (!empty($vid)) {
      $properties['vid'] = $vid;
    }
    $terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadByProperties($properties);
    $term = reset($terms);

    return !empty($term) ? $term->id() : 0;
  }

?>

链接的博客文章似乎不再加载。发现这一点可能对其他试图弄清这一点的人有所帮助。btmash.com/article/2016-04-26/...
gcalex5

34

您可以像使用entityTypeManager一样使用代码段代码:

$term_name = 'Term Name';
$term = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->loadByProperties(['name' => $term_name]);

2

重命名的返回多个值的分类功能taxonomy_get_term_by_name($name, $vocabulary = NULL)已更名taxonomy_term_load_multiple_by_name($name, $vocabulary = NULL)。如果您查看第一个函数的代码并将其与第二个函数的代码进行比较,您会发现最相关的区别是使用替换了对taxonomy_term_load_multiple(array(), $conditions)的调用entity_load_multiple_by_properties('taxonomy_term', $values)

// Drupal 7
function taxonomy_get_term_by_name($name, $vocabulary = NULL) {
  $conditions = array('name' => trim($name));
  if (isset($vocabulary)) {
    $vocabularies = taxonomy_vocabulary_get_names();
    if (isset($vocabularies[$vocabulary])) {
      $conditions['vid'] = $vocabularies[$vocabulary]->vid;
    }
    else {
      // Return an empty array when filtering by a non-existing vocabulary.
      return array();
    }
  }
  return taxonomy_term_load_multiple(array(), $conditions);
}
// Drupal 8
function taxonomy_term_load_multiple_by_name($name, $vocabulary = NULL) {
  $values = array('name' => trim($name));
  if (isset($vocabulary)) {
    $vocabularies = taxonomy_vocabulary_get_names();
    if (isset($vocabularies[$vocabulary])) {
      $values['vid'] = $vocabulary;
    }
    else {
      // Return an empty array when filtering by a non-existing vocabulary.
      return array();
    }
  }
  return entity_load_multiple_by_properties('taxonomy_term', $values);
}

由于taxonomy_term_load_multiple_by_name()尚未标记为已弃用,因此您仍可以在以前使用的地方使用该功能taxonomy_get_term_by_name()。它们都需要相同的参数,因此在这种情况下,将Drupal 7的代码转换为Drupal 8的代码仅是替换函数名。


0

您还可以使用实体字段查询按术语上的字段进行加载

$result = \Drupal::entityQuery('taxonomy_term')
          ->condition('field_my_field_name', 'Whatever Value')
          ->execute();

0

要在Drupal 8中按术语名称加载单个术语ID-

$term = \Drupal::entityTypeManager() ->getStorage('taxonomy_term') ->loadByProperties(['name' => $term_name, 'vid' => 'job_category']); $term = reset($term); $term_id = $term->id();

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.