Have a look at taxonomy_get_parents() and taxonomy_get_parents_all().
You could copy most of the functions but skip
$parents[$tid] = taxonomy_term_load_multiple($tids);
to not load the terms.
/**
* Load a terms parent.
*/
function MODULE_taxonomy_get_parents($tid) {
$parents = &drupal_static(__FUNCTION__, array());
if ($tid && !isset($parents[$tid])) {
$query = db_select('taxonomy_term_data', 't');
$query->join('taxonomy_term_hierarchy', 'h', 'h.parent = t.tid');
$query->addField('t', 'tid');
$query->condition('h.tid', $tid);
$query->addTag('term_access');
$query->orderBy('t.weight');
$query->orderBy('t.name');
// $tids = $query->execute()->fetchCol();
// $parents[$tid] = taxonomy_term_load_multiple($tids);
$tids = $query->execute()->fetchAll();
$parents[$tid] = $tids;
}
return isset($parents[$tid]) ? $parents[$tid] : array();
}
/**
* Load all parents for a term.
*/
function MODULE_taxonomy_get_parents_all($tid) {
$cache = &drupal_static(__FUNCTION__, array());
if (isset($cache[$tid])) {
return $cache[$tid];
}
$parents = array();
if ($term = taxonomy_term_load($tid)) {
$parents[] = $term;
$n = 0;
// while ($parent = taxonomy_get_parents($parents[$n]->tid)) {
while ($parent = MODULE_taxonomy_get_parents($parents[$n]->tid)) {
$parents = array_merge($parents, $parent);
$n++;
}
}
$cache[$tid] = $parents;
return $parents;
}
If you don't need any access control or sorting you can just query the taxonomy_term_hierarchy
table directly.
$query = db_select('taxonomy_term_hierarchy', 'h');
$query->addField('h', 'parent', tid);
$query->condition('tid', $tid);
$query->condition('parent', 0, '!=');
$tids = $query->execute()->fetchAll();
$parents[$tid] = $tids;