I have a question about relations... or maybe its also about making queries. First I want to select a set of data, and then I want to select a subset of that data, based on a relatedTo call.

If I first do this:

{% set caseEntries = craft.entries.section('case').relatedTo({ targetElement: creatorEntry, field: 'creator' }) %}

then, to get a sub-set of what I got before, do this:

{% set caseEntries = caseEntries.relatedTo('and', { targetElement: categoryEntry, field: 'caseCategories' }) %}

it seems as if the first relation is “forgotten” (note that it wont work if I dont include an “and” in the second related to call). Do I have to add the first relation in the second call? Feels like repeating myself... I want to avoid doing this:

{% set caseEntries = caseEntries.relatedTo('and', { targetElement: creatorEntry, field: 'creator' }, { targetElement: categoryEntry, field: 'caseCategories' }) %}

Second relatedTo call overrides first one. Calling it again won't add more parameters to the query.

If you don't want to repeat yourself you can always do this:

{% set creatorRelated = { targetElement: creatorEntry, field: 'creator' } %}

{% set caseEntries = craft.entries.section('case').relatedTo(creatorRelated) %}

{% set caseEntries = caseEntries.relatedTo('and', creatorRelated, { targetElement: categoryEntry, field: 'caseCategories' }) %}
| improve this answer | |

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.