1

I'm trying to find all terms in a vocabulary associated with the current node, that do not have any children.

The most obvious way might be to use taxonomy_get_tree() and match with the returned array to find the childless. Another way is to use a function like this one, and it involves a MySQL query. While my current taxonomy is small and the performance concerns are minimal, I would like to avoid this if this info is already available somewhere.

So, how can I find the depth of a taxonomy term, in a more performance friendly way?

5

The data for taxonomy is in the database. If you want to get that data there is no way to do so without running a database query.

Any function that retrieves this data (including taxonomy_get_tree() and the function you link to above) has to run database queries to get at the data.

taxonomy_get_tree() is a bit heavy so I'd advise using the term_depth function you link to. If you want to increase performance slightly you can improve that function to offer a static page load cache. This will only make a difference if you call the function more than once in a single page load though:

function term_depth($tid) {
  static $depths = array();

  if (!isset($depths[$tid])) {
    $parent = db_result(db_query("SELECT parent FROM {term_hierarchy} WHERE tid = %d", $tid));
    if ($parent == 0) {
      $depths[$tid] = 1;
    }
    else {
      $depths[$tid] = 1 + term_depth($parent);
    }
  }

  return $depths[$tid];
}

Short of building your own cache mechanism that doesn't rely on the database (which would be a massive amount of overkill for this situation) I don't see any way of making this more performant.

  • C'mon Drupal, it was just one more detail, aside from the fairly exhaustive data inside $node :( This would have made my life so much more easy! – Aditya M P Mar 14 '12 at 8:56
  • Thank you for the suggestion on making it a static variable. That will indeed help the speed... – Aditya M P Mar 14 '12 at 8:57
4

Drupal 7 version of Clive's answer:

/**
 * Find the depth of a term
 */
function term_depth($tid) { 
  static $depths = array();

  if (!isset($depths[$tid])) { 
    $parent = db_select('taxonomy_term_hierarchy', 'th')
      ->fields('th', array('parent'))
      ->condition('tid', $tid)
      ->execute()->fetchField();

    if ($parent == 0) { 
      $depths[$tid] = 1;
    } 
    else { 
      $depths[$tid] = 1 + term_depth($parent);
    } 
  } 

  return $depths[$tid];
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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