2

With the addition of the null-coalescing operator (??) in Twig, it now appears that the following two examples both provide a way to retrieve the first entry and fallback to null if no entry exists:

{# Get the first entry using the `first` method on the ElementCriteriaModel #}
{% set entry = craft.entries.section('news').first() %}

{# Get the first entry by accessing it in the result array directly #}
{% set entry = craft.entries.section('news').limit(1)[0] ?? null %}

It seems, with the addition of eager-loading and the alternative results syntax required for accessing eager-loaded elements in our templates, that the latter option may provide a consistent syntax to use throughout our templates vs. swapping between the former and the latter depending on which type of query you are performing.

Aside from the uglier syntax in the option that uses the null-coalescing operator, are there any other tradeoffs to consider in choosing the first method vs. the null-coalescing method when retrieving a single entry?

  • 1
    Good question! Also, worth bringing this plugin in to the discussion as a sort of third alternative: github.com/marionnewlevant/craft-mn_eager Personally I would like some (ideally syntactically nice) way of dealing with eager vs. not eager that does not require a plugin... – Jeremy Daalder Mar 21 '16 at 1:49
1

My gut says the first option (.first()) is going to be slightly faster, but in real world performance my guess is that it's negligible.

Personally, I think I'd prefer the cleaner, more explicit, syntax of the first.

| improve this answer | |
0

I noticed that there's quite a big difference in query performance between using first and find if there are many element models matching your criteria. See the example in this answer for some measurements:

Optimizing pagespeed

In that example, there are lots of images related to each entry queried. It would be interesting to see how it would perform with eager loading. Might be that first is still faster, as you wouldn't get back all the models and you can't (yet?) query for the first element only with eager loading. Probably worth a feature request.

| improve this answer | |
  • Right, the bottleneck with find() matching many elements is all of the model overheard when its populating all of those models from the element matches. No longer an issue in Craft 3, but even on Craft 2 matching 1 element is trivial. – Brad Bell Mar 21 '16 at 18:50

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.