4

I have a page with a lot of entries fields. They are awesome but that leads also to a LOT of db requests.

Aside from caching are there some best practices to lower db requests on entries fields?

For example my whole navigation is built with entries fields:

{% for entry in globalsNavi.businessSorter %}
    <a href="{{ entry.url }}">{{ entry.title }}</a>
{% endfor %}

Would it make any difference if I grabbed only url and title in this example since there are a lot more fields available. And if it would make a difference how would I have to write this?

Something like:

{% for entry in globalsNavi.businessSorter( entry.title, entry.url ) %}
Brad Bell
  • 67,440
  • 6
  • 73
  • 143
KSPR
  • 3,786
  • 2
  • 29
  • 52

1 Answers1

6

This is how relationships work in Craft at the moment. Each relation equals +1 query. If you don't access your relation on an entry the query isn't executed. So by only fetching title and/or id you don't run any extra relationship queries.

Caching is your best option at the moment to make the query count go down. Make use of caching to cache large chunks of you code.

Brandon has hinted on Slack that Craft3 might incorporate Yii2 lazy loading of relations using the ->with() command. This will solve a lot of the N+1 queries with relationships.

Update

The release of Craft 2.6 included the functions for Eager-Loading of elements. See this link for documentation on the subject: https://craftcms.com/docs/templating/eager-loading-elements

naboovalley
  • 2,844
  • 1
  • 16
  • 26