Eager-loading and custom selects and/or query execution #16714
-
Is it possible to combine eager-loading with a custom select and/or query execution? Take this template that uses lazy eager-loading for {% set news = craft.entries().section('news').all() %}
{% for news_entry in news %}
{% set categories = news_entry.news_categories.eagerly().all() %}
{# … #}
{% endfor %} But actually, I only need the {% set categories = news_entry.news_categories.select('title').column() %} But of course this results in an N+1 problem. I tried combining this with {% set categories = news_entry.news_categories.eagerly().select('title').column() %} But the amount of queries used stays the same compared to the previous snippet, so I don't think this is supported?
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
It’s only possible to eager-load (normally or lazily) entire elements, not individual values. I’d stick with your first example. Less queries, simpler/more future-proof code, and better cachability. (By accessing |
Beta Was this translation helpful? Give feedback.
It’s only possible to eager-load (normally or lazily) entire elements, not individual values.
I’d stick with your first example. Less queries, simpler/more future-proof code, and better cachability. (By accessing
category.title
, a cache invalidation tag will be registered for the category, so any surrounding{% cache %}
tags, etc., will be cleared whenever the category is updated.)