2

I'm currently working on a relation-heavy website with a colleague of mine and, for that reason, eager-loading stuff looks very appealing to us. We've succeeded in eager-loading pretty much everything that we needed but there is just one kind of template that we couldn't make it work with: paginated archives

The context: We have this archive page that loads every entry of a 'projects' section and, next to each entry, we have a list of all images that the entry contains which is between 8-20 images (remember, I said it was relation-heavy ;) ). We care a lot about performance so we decided to paginate this big entry listing.

The issue: All this works very well except that when we tried to eager-load those images, we transformed our original query which was:

{% set allProjects = craft.entries(queryParams).limit(itemsPerPage) %}

to

{% set allProjects = craft.entries(queryParams).limit(itemsPerPage).find({
    with: [
        'gridMatrixBlock1:rowItem1',
        ['gridMatrixBlock1:rowItem1.gridimageFile', {
            kind: 'image',
            withTransforms: projectThumb
        }],
        ...
    ]
}) %}

The question: Since .find() returns an array, we have no way to paginate this (pagination need an ElementCriteriaModel). Is there any workaround I don't know about?

1 Answer 1

3

with is just another query param, like limit or whatever parameters you’re defining in entryParams.

The {% paginate %} tag requires that you pass in an ElementCriteriaModel, but as soon as you call find() you’re actually dealing with an array of the matched entries.

So the key to getting eager-loading working with pagination is to assign the with param like any other param, rather than passing it into the find() function.

{% set queryParams = {
    // ...
    with: [
        'gridMatrixBlock1:rowItem1',
        ['gridMatrixBlock1:rowItem1.gridimageFile', {
            kind: 'image',
            withTransforms: projectThumb
        }],
        ...
    ]
} %}

and then you can create your ElementCriteriaModel just like you were doing before:

{% set allProjects = craft.entries(queryParams).limit(itemsPerPage) %}
1
  • That's perfect Brandon! I didn't know we could also do it like this (which I personally prefer). Thanks! Commented Mar 31, 2016 at 10:19

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.