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 ) %}
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

  • 2
    There's a rumor that eager loading of relationships might even make it into Craft 2.6. :) – Brad Bell Feb 23 '16 at 18:55
  • If I could click the upvote button 100000 times I would right now. – naboovalley Feb 23 '16 at 20:10

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.