4

I want to get all taxonomy term in $lang language, following snippet works correctly and return all terms of $lang code.

    $query = \Drupal::entityQuery('taxonomy_term');
    $query->condition('vid', "news_category");
    $query->condition('langcode', $lang);
    $tids = $query->execute();
    //$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);
    return new JsonResponse($tids);

Then I want get results in order that in the taxonomy list they are, try to sort them with $query->sort('weight','ASC'); but with following snippet the results are the same before adding sort.

    $query = \Drupal::entityQuery('taxonomy_term');
    $query->condition('vid', "news_category");
    $query->condition('langcode', $lang);
    $query->sort('weight','ASC');
    $tids = $query->execute();
    //$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);
    return new JsonResponse($tids);

anybody Know where is the problem and how can I get terms in order they are in taxonomy list with entityQuery?

2

Taxonomy overview list uses something like:

  ->sort('weight', 'ASC')
  ->sort('name', 'ASC')

If that doesn't work for you, take a look at \Drupal\taxonomy\TermStorage::loadTree

  • thansk for your attention, but not worked – Yusef Mohamadi Mar 13 '17 at 21:33
  • in my question I write down sort by weight, adding another sort by name couldn't help. This is not WORKS – Yusef Mohamadi Mar 14 '17 at 19:05
1

As was previously suggested, taking a look at \Drupal\taxonomy\TermStorage::loadTree is helpful. Entity Query only provides access to properties of the entity and its Field API values. Since the weight of the term is available in the taxonomy_term_field_data table, it will be available to entityQuery as well. However, any nesting of terms, aka hierarchy, will require access to the taxonomy_term_hierarchy table. That would require a database query.

You can access it via a database query, as seen in loadTree, line 204:

    $query = \Drupal::database()->select('taxonomy_term_field_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
    $result = $query
      ->addTag('taxonomy_term_access')
      ->fields('t')
      ->fields('h', array('parent'))
      ->condition('t.vid', $vid)
      ->condition('t.default_langcode', 1)
      ->orderBy('t.weight')
      ->orderBy('t.name')
      ->execute();

I have updated the query to use Drupal's container, rather than the dependency injection so it can be used more readily. You should be able to modify this to fit your needs if Entity Query is not working as you desire it to.

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.