1

I have 2 categories, model and feature which I've added as a field to an entry. I want to find entries with the model category using "or" but the feature category using "and". I believe the "relatedTo" functionality only allows one kind which is very restrictive.

{% set model = [24, 25, 26] %}
{% set feature = ['AND', 46, 47, 48] %}

{%
    set entries = craft.entries({
        relatedTo: [model, feature]
    })
%}

The code above is an example, but it returns no results. How else can I achieve this?

1

Ok, I was close :P

The trick is to create an object to pass instead of an array. The documentation for this is sketchy and confusing so I hope this snippet helps someone.

Notice I am setting 'and' at the root of the object, but this only applies to the objects that follow, not to targetElement arrays. So by separating all the features into separate objects, the 'and' is applied to them, but not the models.

{% set models = [24, 25, 26] %}
{% set features = [46, 47, 48] %}

{%
  set relatedTo = ['and', {
    targetElement: models,
    field: 'model'
  }]
%}

{% for feature in features %}
  {% set relatedTo = relatedTo|merge([{
    targetElement: feature,
    field: 'feature'
  }]) %}
{% endfor %}

{%
  set entries = craft.entries({
    relatedTo: relatedTo
  })
%}

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.