Can a return schema be specified for entry queries? I'd only like the titles instead of the whole entry.
2 Answers
Yes, you can change both the columns to be selected and execute queries in several ways to get the results in different formats. In this case, you want to use select()
to select the title
column and execute the query with column()
to get an array of titles instead of an array of Entry
objects.
{% set entryTitles = craft.entries()
.select('title')
.column()
%}
Check out the documentation on Advanced Element Queries for details.
If you want to select multiple columns at once, you can use asArray
to get an array of associative arrays instead of entry objects. Note that if you want to select custom fields (instead of native properties like title
), you need to include both the field prefix and suffixes in the column name – see this question for details.
@MoritzLost's answer should be the accepted one. But, as an alternative approach you could also use the |map
Twig filter to "prune" the entry objects returned from a normal element query:
To create an array containing only entry titles:
{% set entryTitles = craft.entries.all()|map(entry => entry.title) %}
Edit: As suggested by MoritzLost in the comments, an even simpler way to retrieve an array of single values is by using the |column
filter:
{% set entryTitles = craft.entries.all()|column('title') %}
To create an array of objects containing multiple values – for example, the title and a custom heading
field:
{% set entries = craft.entries.all()|map(entry => { title: entry.title, heading: entry.heading }) %}
Between the two approaches, using Advanced Element Queries to only fetch the column(s) that you need will probably be a bit faster - but unless this is a massive dataset, the actual difference is likely going to be completely negligible – while the big benefit with the |map
(or |column
) approach over Advanced Element Queries is that you won't have to worry about custom field prefixes or suffixes.
-
2Good caveat – note that the first example can be simplified still using the
column
filter:{% set entryTitles = craft.entries.all()|column('title') %}
Mar 17, 2022 at 9:42 -
1