You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/5.x/development/eager-loading.md
+3-20Lines changed: 3 additions & 20 deletions
Original file line number
Diff line number
Diff line change
@@ -78,7 +78,7 @@ Element queries in Craft 5 have a new `.eagerly()` query param that simplifies e
78
78
.all() %}
79
79
80
80
{% for post in posts %}
81
-
{% set image = post.featureImage|first %}
81
+
{% set image = post.featureImage.one() %}
82
82
83
83
<article>
84
84
<h2>{{ post.title }}</h2>
@@ -145,8 +145,7 @@ Here’s how to apply the `with` param to our example:
145
145
.all() %}
146
146
147
147
{% for entry in entries %}
148
-
{# Get the “first” (or only) eager-loaded asset: #}
149
-
{% set image = entry.assetsField|first %}
148
+
{% set image = entry.assetsField.one() %}
150
149
151
150
{# Make sure we actually have an asset element: #}
152
151
{% if image %}
@@ -161,22 +160,6 @@ This template code will only cost three queries (one to fetch the entries, one t
161
160
162
161
Eager-loaded elements are returned as a [collections](collections.md)—or more specifically, an <craft5:craft\elements\ElementCollection>. This means that (in most cases) eager-loaded and non-eager-loaded elements can be treated in the same way.
163
162
164
-
There are some differences in the methods exposed by element queries and
165
-
166
-
Accessing eager-loaded elements works a little differently than regular elements, under certain circumstances. Take a look at how we assigned the `image` variable in our examples, before and after applying the `with` param:
167
-
168
-
```twig
169
-
{# Before: #}
170
-
{% set image = entry.assetsField.one() %}
171
-
172
-
{# After: #}
173
-
{% set image = entry.assetsField|first %}
174
-
```
175
-
176
-
When the assets _aren’t_ eager-loaded, `entry.assetsField` gives you a preconfigured [asset query](../reference/element-types/assets.md#querying-assets) to return the related assets.
177
-
178
-
However, when the assets _are_ eager-loaded, `entry.assetsField` gets overwritten with an array of the eager-loaded assets. So `one()`, `all()`, and other element query methods are not available. Instead you must stick to the standard array syntaxes. In our example, we’re grabbing the first asset with `entry.assetsField[0]`, and we’re using Twig’s _null-coalescing operator_ (`??`) to define a default value (`null`) in case there is no related asset.
179
-
180
163
## Eager-Loading Multiple Sets of Elements
181
164
182
165
If you have multiple sets of elements you wish to eager-load via the primary query, add those field handles to your `.with()` parameter:
@@ -224,7 +207,7 @@ It’s also possible to optimize loading of elements nested two or more levels d
0 commit comments