12

I am a little confused about the differences between an elementCriteriaModel and fetched elements.

Why do I sometimes have to fetch elements with first(), last(), find():

{% set entries = craft.entries.section('cocktails').find() %}

and in other cases the elementCriteriaModel is enough:

{% set params = craft.entries.section('cocktails') %}
{% set prev   = entry.getPrev(params) %}

2 Answers 2

19

The ElementCriteriaModel and the individual element models (like the EntryModel) can be thought of as two different points of time in retrieving data from your database. Essentially, you'll use an ElementCriteriaModel before the database is queried and the element models afterwards.

Why do I sometimes have to fetch elements with .first(), .last(), .find()

The ElementCriteriaModel does what it says on the tin — it specifies criteria to find elements. When you call .find(), .first() or .last(), the model sends itself off to the ElementsService which will return element models, based on your criteria.

…and in other cases the ElementCriteriaModel is enough?

Internally, Craft is using ElementCriteriaModels to work things out. For pagination or the .getPrev() example, Craft is finding elements using the same criteria, but it's using it in a different way to .find() or similar methods.

You can omit the .find() method and treat the ElementCriteriaModel as an array, but it depends on your scenario. As was touched on here, there are performance impacts to consider.

2
  • Definitely a better answer...I'm voting for yours! Commented Jun 18, 2014 at 14:43
  • Elegant and succinct. Great answer!
    – Matt Stein
    Commented Jun 18, 2014 at 14:46
2

From the docs:

Treating your ElementCriteriaModel object as an array will get it to act like one, too. (No find() necessary!)

See the fourth point here.

2
  • But in what cases do I need the model and in what the fetched elements? For example pagination needs the model. -- And if it gets added automatically does that mean that I never need to add .find() ? (Assuming I don't pass parameters in it)
    – Victor
    Commented Jun 18, 2014 at 12:36
  • I'm not completely sure of all the different cases but I know that when using relatedTo() you can just give it the model. I think most of the times you can actually do both, maybe pagination is a one off here (@bradbell or @brandonkelly will know more). Its certainly worth playing with in various cases though as in one example I found using .ids() over just the model was a significant performance increase. Commented Jun 18, 2014 at 12:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.