1

I'm trying to find all tiers that have associated entries for a selection dropdown.

This does not work, and throws a 502 error

{% set allTeirs = craft.categories.group('catPartnerTeirs') %}
{% set partnersWithTeirs = allPartnerEntries.relatedTo(allTeirs).limit(null) %}
{% set partnerTeirsInUse = allTeirs.relatedTo(partnersWithTeirs).all() %}

This does work, but results in duplicate DB queries:

{% set allTeirs = craft.categories.group('catPartnerTeirs') %}
{% set partnersWithTeirs = allPartnerEntries.relatedTo(allTeirs).limit(null) %}
{% set partnerTeirsInUse = craft.categories.group('catPartnerTeirs').relatedTo(partnersWithTeirs).all() %}

Can someone explain to me why? I've dumped them both to the page (the set variable and the query itself and they both return exactly the same object, so far as I can tell.

I'm also totally open to better ways of finding "Tiers that have associated entries", if you've got that too.

1
  • Can you add the query for allPartnerEntries so we can see what that looks like? allTeirs should be a list of categories, allPartnerEntries should return a list of entries, partnerTeirsInUse should return a list of categories (possibly shorter than allTeirs). What do you get? Jan 18 at 16:39

1 Answer 1

1

Typically I use an ids() query to do that kind of thing, as it is usually more efficient than a full-blown .all(), like this:

{% set allPartnerIds = craft.entries.section('partners').limit(null).ids() %}
{% set tiersInUse = craft.categories.group('catPartnerTeirs').relatedTo(allPartnerIds).all() %}

If you have already queried for the partner entries elsewhere in the template, you could avoid any extra queries by using the column filter like this:

{% set allPartnerIds = allPartnerEntries|column('id') %}
{% set tiersInUse = craft.categories.group('catPartnerTeirs').relatedTo(allPartnerIds).all() %}

(though you should be fine to pass in the actual elements instead of their ids - you just need to ensure that the element query is executed (i.e., with .all()).

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.