0

I tried to find a method to verify if the current taxonomy item page has a parent or children, now I get two but I don't know which one is better for the efficiency.

approach I: use taxonomy item controller

$tid = \Drupal::routeMatch()->getRawParameters('taxonomy_term');
$term = taxonomy_term_load($tid);
$items = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadChildren($tid,$term->getVocabularyId());

approach II: database query

$db = \Drupal::database();
$query = $db->select('taxonomy_term__parent','ttp')->condition('ttp.parent_target_id',$tid)->fields('ttp',['entity_id']);
$result = $query->execute()->fetchAll();

Both method can satisfy my initial demand, but which one is better in efficiency? And what about the general case, when we need to check some data, using the data object method or database query, which is better?

  • It's very rare you should directly query data from the DB in Drupal, as you will lose out on any entity caching or the like, which may (depending on your setup) bypass the DB altogether (which is much more efficient). As such, I'd suggest using controllers by default. – Jaypan Jan 10 at 9:08
1

Do you need to load all of the children? Otherwise, loadChildren() will be performing the same query but also loading the full term -- which is a performance dent. The API on the entity storage won't make much of a difference here, honestly.

Have you looked at https://www.drupal.org/project/taxonomy_term_depth? This would be more performant. It caches the depth level in a new base field. If a term's depth is greater than one, you know it is a child.

I would even borrow the concepts from taxonomy_term_depth to add a new base field that is a boolean which caches if the term has children or not. That way you only need to work with the current term entity.

  • No, I don't need to load all children. I only want to check if the current item has children or not. Thanks for your recommend, I'll think about that. – richardson Jan 11 at 6:38
0

If you only want to know which method is quicker, you need to benchmark them in the context of how they're being used in your particular site.

But generally speaking, using the API is always better:

  • It improves performance over time by enabling you to use the entity cache (direct querying obviously doesn't give you that)
  • You're programming to the interface, and not the implementation. The underlying database structure could theoretically change with the next release, leaving you with a load of code to update if you choose not to use the API.

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.