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
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
.
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;
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.
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.
-
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 -
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();
}
-
1The OP asked for the machine name of the vocabulary, not the label. So the correct answer would be the
$vid
I guess.– berlinerCommented Apr 24, 2022 at 21:32