<p>This feature has now made it into Craft core <a href="https://craftcms.com/news/craft-cms-2-6-commerce-1-1" rel="nofollow">as of version 2.6</a>. </p>

<p>See this link for documentation on the subject:<br>
<a href="https://craftcms.com/docs/templating/eager-loading-elements" rel="nofollow">https://craftcms.com/docs/templating/eager-loading-elements</a></p>

CC BY-SA 3.0
2016-03-11T10:27:23.650Z
2016-08-05T04:21:25.707Z
2016-08-05T04:21:25.707Z
naboovalley
<p>I've been thinking about ways to achieve this recently, and I've put together a basic proof-of-concept plugin for fetching one level of relations for a collection of elements, with no more than two extra queries for each element type.</p>

<p>One query to get the IDs of the related elements, and then another to actually fetch and return the elements with the <code>ElementsService</code>.</p>

<p>The plugin then matches those related elements back to the entries through a dynamically-added <code>fetched()</code> method.</p>

<p>Say you want to fetch all the Assets related through the <code>mainImage</code> and <code>additionalImages</code> fields, over a collection of product entries:</p>

<pre><code>{% set entries = craft.entries.section('products').find %}
{% do craft.fetch.assets(entries, 'mainImage, additionalImages') %}

{% for entry in entries %}
    {% if entry.fetched('mainImage')|length %}
        &lt;img src="{{ (entry.fetched('mainImage')|first).getUrl('large') }}"&gt; 
    {% endif %}

    {% for image in entry.fetched('additionalImages') %}
        &lt;img src="{{ image.getUrl('medium') }}"&gt; 
    {% endfor %}
{% endfor %}
</code></pre>

<p>I wouldn't say it's <em>necessarily</em> production-ready yet, but I've thrown it up on Github - <a href="https://github.com/mdcpepper/fetch" rel="nofollow">https://github.com/mdcpepper/fetch</a></p>

CC BY-SA 3.0
2015-03-04T16:16:52.617Z
Very cool Mike! I think something like this is definitely on the right track.
Peter Tell
CC BY-SA 3.0
2016-08-05T02:44:49.653Z
As noted in another answer, this functionality is now in Craft core, [as of version 2.6](https://www.cmscritic.com/craft-cms-rolls-out-craft-2-6-craftcommerce-1-1-with-eager-loading-support/).
Simon East
CC BY-SA 3.0
2015-03-04T13:37:44.530Z
2015-03-08T04:56:48.553Z
2015-03-08T04:56:48.553Z
Mike Pepper
<p>Sure thing.</p>

<pre><code>$groupRecord = FieldGroupRecord::model()-&gt;with('fields')-&gt;findById($groupId);
</code></pre>

<p>That will eager load the related data from the "fields" table with the "fieldgroups" table.</p>

CC BY-SA 3.0
2014-10-17T17:20:26.643Z
Oh duh, I don't know how I missed that Craft Records inherit that. I'll experiment. Thanks!
Chris Lewis
CC BY-SA 3.0
2014-10-19T14:44:30.533Z
After some experimentation, I've updated the question to better reflect what I should have asked originally.
Chris Lewis
CC BY-SA 3.0
2014-10-19T14:53:48.077Z
Or, if there is an `EntryRecord`-based way to eagerly load relations from a Craft field, I'll happily take that :)  e.g. the equivalent of this: `$entry->children->with('assetsField')->find()`
Chris Lewis
CC BY-SA 3.0
2014-12-15T22:03:17.673Z
I'm actually curious about this too as it relates to grabbing entries and pulling in their associated relationships. i.e., for an entry that has "x" associated images and "x" associated entries, eager load all those relationships in one (or two) DB calls
Peter Tell
CC BY-SA 3.0
2014-10-16T16:57:06.810Z
2014-10-16T16:57:06.810Z
Brad Bell
<p>Is there any way to "eagerly load" Craft element relations a la Yii's ActiveRelation "with" function?</p>

<p><a href="http://www.yiiframework.com/doc/api/1.1/CActiveRecord#with-detail">http://www.yiiframework.com/doc/api/1.1/CActiveRecord#with-detail</a></p>

<p>This seems like a very handy way to request one big query instead of many small ones in cases where you know up front that you are going to be using all the relations.</p>

<p>** UPDATE **</p>

<p>Okay after experimenting with this, I guess my real question should have been, is there any way to do this kind of thing at the ElementCriteriaModel level, taking advantage of Craft relational fields.</p>

<p>For instance, I want to get a list of children of a Structure entry, along with all the assets in a field:</p>

<pre><code>foreach ($entry-&gt;children-&gt;find() as $child) {
    // do something with $child-&gt;assetsField...
}
</code></pre>

<p>Is there any way to load those assets in one big query rather than individually for each child?</p>

CC BY-SA 3.0
2014-10-16T20:21:33.080Z
Which “relations” are you referring to? Active record relations (e.g. what the with() method is for), or Craft [element relations](http://buildwithcraft.com/docs/relations)?
Brandon Kelly
CC BY-SA 3.0
2014-10-17T17:19:56.297Z
Sorry, I should have made it clear. I'm talking about Craft element relations. Edited the question to clarify.
Chris Lewis
<database><relations>
"Eager loading" of relations like Yii's "with" function
# "Eager loading" of relations like Yii's "with" function

(Asked by: username_0 on 2014-10-16)

Is there any way to "eagerly load" Craft element relations a la Yii's ActiveRelation "with" function?
http://www.yiiframework.com/doc/api/1.1/CActiveRecord#with-detail
This seems like a very handy way to request one big query instead of many small ones in cases where you know up front that you are going to be using all the relations.
** UPDATE **
Okay after experimenting with this, I guess my real question should have been, is there any way to do this kind of thing at the ElementCriteriaModel level, taking advantage of Craft relational fields.
For instance, I want to get a list of children of a Structure entry, along with all the assets in a field:
foreach ($entry->children->find() as $child) {
    // do something with $child->assetsField...
}

Is there any way to load those assets in one big query rather than individually for each child?

**Tags:** database, relations
> **Comments:**
> **username_1**: Which “relations” are you referring to? Active record relations (e.g. what the with() method is for), or Craft [element relations](http://buildwithcraft.com/docs/relations)?  
> **username_0**: Sorry, I should have made it clear. I'm talking about Craft element relations. Edited the question to clarify.  

---

## 3 answers

### Answer by username_2 on 2016-03-11. Score: 7

This feature has now made it into Craft core [as of version 2.6](https://craftcms.com/news/craft-cms-2-6-commerce-1-1).

See this link for documentation on the subject:  
<https://craftcms.com/docs/templating/eager-loading-elements>


---

### Answer by username_3 on 2015-03-04. Score: 6

I've been thinking about ways to achieve this recently, and I've put together a basic proof-of-concept plugin for fetching one level of relations for a collection of elements, with no more than two extra queries for each element type.
One query to get the IDs of the related elements, and then another to actually fetch and return the elements with the ElementsService.
The plugin then matches those related elements back to the entries through a dynamically-added fetched() method.
Say you want to fetch all the Assets related through the mainImage and additionalImages fields, over a collection of product entries:
{% set entries = craft.entries.section('products').find %}
{% do craft.fetch.assets(entries, 'mainImage, additionalImages') %}

{% for entry in entries %}
    {% if entry.fetched('mainImage')|length %}
         
    {% endif %}

    {% for image in entry.fetched('additionalImages') %}
         
    {% endfor %}
{% endfor %}

I wouldn't say it's necessarily production-ready yet, but I've thrown it up on Github - https://github.com/mdcpepper/fetch

> **Comments:**
> **username_4**: Very cool Mike! I think something like this is definitely on the right track.  
> **username_5**: As noted in another answer, this functionality is now in Craft core, [as of version 2.6](https://www.cmscritic.com/craft-cms-rolls-out-craft-2-6-craftcommerce-1-1-with-eager-loading-support/).  

---

### Answer by username_6 on 2014-10-16. Score: 3

Sure thing.
$groupRecord = FieldGroupRecord::model()->with('fields')->findById($groupId);

That will eager load the related data from the "fields" table with the "fieldgroups" table.

> **Comments:**
> **username_0**: Oh duh, I don't know how I missed that Craft Records inherit that. I'll experiment. Thanks!  
> **username_0**: After some experimentation, I've updated the question to better reflect what I should have asked originally.  
> **username_0**: Or, if there is an `EntryRecord`-based way to eagerly load relations from a Craft field, I'll happily take that :)  e.g. the equivalent of this: `$entry->children->with('assetsField')->find()`  
> **username_4**: I'm actually curious about this too as it relates to grabbing entries and pulling in their associated relationships. i.e., for an entry that has "x" associated images and "x" associated entries, eager load all those relationships in one (or two) DB calls  

---

