3

If I've got an array of entries, is there a less long winded approach to convert that to an array of ids so I can use it in another lookup.

{# Look up authors that match the entered query.
{% set authorEntries = craft.users.search('fullName:*' ~ query ~ '*')|default([]) %}

{% set authorIds = [] %}
{% for author in authorEntries %}
    {% set authorIds = authorIds|merge([author.id]) %}
{% endfor %}

Thanks!

5

Simply append .ids() to your initial query...

{% set authorIds = craft.users.search('fullName:*' ~ query ~ '*').ids() %}

Without the .ids() method, you're actually working with an Element Criteria Model.

The behavior that you're seeing is the default... it's as if you had appended .find() to your initial query.

[.find()] will be called automatically as soon as the ElementCriteriaModel is treated like an array (that is, as soon as you... start looping through the elements)

So instead of allowing the default behavior to kick in, just apply .ids() to the initial query, and get a batch of entry IDs instead of a full array of entries

| improve this answer | |
1

Lindsey's answer should be the accepted one, but just for kicks – here's an additional approach that makes sense if you need an array of IDs and you want to loop over the entries, as well. Calling .ids() on the ElementCriteriaModel will result in an additional database query, but using the |group and |keys filters won't:

{% set authorEntries = craft.users.search('fullName:*' ~ query ~ '*').find() %}
{% set authorIds = authorEntries|group('id')|keys %}

{% for authorId in authorIds %}
    ...
{% endfor %}

{% for author in authorEntries %}
   ...
{% endfor %}
| improve this answer | |
  • Oh that's cool. Thanks Mats. Craft is tied so nicely in with Twig! – JamesNZ Oct 6 '16 at 22:51

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.