1

I am trying to add eager loading to a query. The original query was as follows (‘sticky’ is a custom lightswitch field for marking sticky entries):

{% set news = craft.entries.section('news').order('sticky desc, postDate desc').limit(9) %}

Is the following ok syntax for adding eager loading?

{% set news = craft.entries.section('news').order('sticky desc, postDate desc').limit(9).find({
    with: [
        ['newsHighlightImage', {
            withTransforms: ['newsMedium', 'newsSmall']
        }]
    ]
}) %}

I ask because although the above seems to work, in the examples in the documentation, the find/with bits come right after the section parameter. But if I do it that way, I get an error about not being able to apply the “order” method. I reckon that’s because find() turns the result into an array so “order” is not longer available. But I couldn’t figure out the correct carry syntax to make it work that way. Is there a better way to do this?

Thanks!

Willhaus

1

How about stacking all the element query params into a single object?

{% set entries = craft.entries({
    section: 'news',
    order: 'sticky desc, postDate desc',
    limit: 9,
    with: [
        ['newsHighlightImage', {
            withTransforms: ['newsMedium', 'newsSmall']
        }]
    ]
}) %}

Also, I don't believe you need to use the find() function here. The examples in the documentation only use find() when eager-loading just the image transforms related to a single asset field.

{% set assets = entry.assetsField.find({
    withTransforms: [
        'heroImage',
        { width: 100, height: 100 }
    ]
}) %}
  • Tried it and it works, thank you. Funny thing is that I was going to say it seems at first that it's exactly like mine but with a different syntax, but dev mode says it run one additional query than mine for some reason… – Willhaus Sep 10 at 2:42
  • ¯_(ツ)_/¯ Eager loading magic? Who knows. Also magnets... how do they work? ;) – Alex Roper Sep 10 at 5:26

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.