1

Is there any table in the database that shows the relationship between vocabulary and taxonomy, or is there any way to find out the vocabulary name of a particular taxonomy from its tid?

4 Answers 4

3

The table taxonomy_term_data lists the terms, and taxonomy_vocabulary lists the vocabularies.

In the table taxonomy_term_data, the term string is found in the name field. The field vid identifies the vocabulary assocaiated with the term. And the field tid is the numeric taxonomy id.

So you can look up the relationship between the term name, tid and vid directly from the this table.

Then, to determine the vocabulary name string associated with the term, you need to left join the taxonomy_vocabulary.name field, where taxonomy_vocabulary.vid = taxonomy_term_data.vid.

3

Using the API would be preferable to going into the database directly as you can take advantage of caching properly, and keep a more structured code base at the same time:

$term = taxonomy_term_load($tid);
$vocab = taxonomy_vocabulary_load($term->vid);
$machine_name = $vocab->machine_name;
3

If you have the taxonomy term ID, it is enough you call taxonomy_term_load().

$term = taxonomy_term_load($tid);
$vocabulary_name = $term->vocabulary_machine_name;

Using the Devel module, you can notice the object returned from taxonomy_term_load() contains the following fields.

screenshot

With Drupal 8, each entity has its own PHP class, contrary to previous Drupal versions where each entity instance is a stdClass object.

In Drupal 7, if you don't have a taxonomy term ID, and you want to load all the taxonomy terms, you should use the EntityFieldQuery class; see How to use EntityFieldQuery. In Drupal 8, entity_load_multiple_by_properties() is the function you should use.

2
  • Indeed, TaxonomyTermController::buildQuery() joins in the vocab table to get that value when you use taxonomy_term_load(). You learn something new every day :)
    – Clive
    Commented May 25, 2013 at 12:42
  • So; how would you load the machine_name in Drupal 8?
    – sea26.2
    Commented Mar 24, 2020 at 17:25
0

With D8 something like this.

$parameters = \Drupal::routeMatch()->getParameters()->all();
if (isset($parameters['taxonomy_term'])) {
  $term = $parameters['taxonomy_term'];  
  $vid = $term->bundle();
  $vocabulary = \Drupal::entityTypeManager()->getStorage('taxonomy_vocabulary')->load($vid);
  $vocabulary_label = $vocabulary->label();
}
1
  • 1
    The OP asked for the machine name of the vocabulary, not the label. So the correct answer would be the $vid I guess.
    – berliner
    Commented Apr 24, 2022 at 21:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.