6

I want to be able to return all entries that are related to 1 .. n categories:

{% set resources = craft.entries.section('resources').relatedTo('and', categories) %}

in this example, categories contains two categories category1 and category2, and the query returns all entries that have either category1 or category2.

How do I change the syntax to return entries that are related to both category1 and category2?

I thought 'and' would do it, but seemingly not.

9

That and argument only applies to the other top-level relatedTo arguments. If one of those arguments targets multiple elements (e.g. categories), those will still be glued together with “OR”.

You would need to set it up like this instead:

{% set resources = craft.entries.section('resources').relatedTo(
    'and',
    { targetElement: category1 },
    { targetElement: category2 }
) %}

If you don’t know all of the categories ahead of time, you can create the parameter value dynamically like this:

{# Get the category IDs #}
{% set catIds = craft.categories[...].ids() %}

{# Create the relatedTo param value #}    
{% set relatedTo = ['and'] %}

{% for id in catIds %}
    {% set relatedTo = relatedTo|merge([id]) %}
{% endfor %}

{# Now find our entries #}
{% set resources = craft.entries.section('resources').relatedTo(relatedTo) %}

Update

This is significantly easier in Craft 2.5 (currently in beta), as the relatedTo param’s element, targetElement, and sourceElement sub-properties can now begin with 'and', which tells Craft to only return elements that are related to all of the following element IDs.

Here’s a quick example:

{# Start with a list of category IDs that must be included #}
{% set catIds = [1, 2] %}

{# Find the entries #}
{% set resources = craft.entries({
    section: 'resources',
    relatedTo: {
        targetElement: ['and']|merge(catIds),
    }
}) %}
  • Hmm okay thanks - is there any way I can loop through categories, since it can contain 1 or more categories depending on parameters – Daniel Sep 28 '14 at 17:16
  • @Daniel Sure, just updated the answer. – Brandon Kelly Sep 28 '14 at 17:23
  • @BrandonKelly Does the original relatedTo syntax no longer work in 2.5? – jthomas Nov 11 '15 at 21:22
  • @jthomas it does, the new syntax is supported in addition to precious syntaxes. – Brandon Kelly Nov 11 '15 at 21:23
  • @BrandonKelly Your updated example is returning an "or" scenario for me. Here is the code I'm using. But manually passing two IDs still gives me entries matching "any" of the category IDs instead of only entries matching "all" category IDs. pastebin.com/2HQjrChj – jthomas Nov 11 '15 at 21:52

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.