1

I’ve been wrestling with a site from another developer (who will not be named). He seems to have a pretty solid grasp of PHP, and I had assumed that he also understood Craft well.

However, as I started to look at his templates, I came across code like this:

{% if
  (entry.productDimensionsImage.one() or
   entry.productSpecifications.one())
%}

I would have written it using count() instead of one(), or if I really needed the entry:

{% set prodDim = entry.productDimensionsImage.one() %}
{% set prodSpc = entry.productSpecifications.one() %}
{% if (prodDim and prodSpc) %}

My main concern is that the exact same queries are being used repeatedly throughout a single template; he’s going back to the database over and over again to check the same entry. Then, after he’s done so half a dozen times, then he finally sets it in a variable to loop through it.

So, is there something I’ve misunderstood? Is there a good reason to keep querying the database multiple times in a single template file?

TIA

3

You're not misunderstanding anything, and your concerns are perfectly valid. I feel like many developers using Craft do not realise that .one() and .all() are in fact database calls, and pretty expensive ones at that. Do it your way, watch the number of DB queries go down in the debug toolbar and feel all warm and fuzzy. (Also, you don't need parentheses in conditionals unless you're doing some complex grouping - {% if prodDim and prodSpc %}).

1

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.