I have two queries on related entries (using Many to Many plugin) to find both related and then reverse related entries:

{% set relatedArticles = article.relatedArticles %}

{% set reverseRelatedArticles = craft.entries.relatedTo(article) %}`

I want to merge these two ElementCriteriaModel, removing any duplicates before processing them further. I've tried this:

{% for item in reverseRelatedArticles %}
    {% if item not in relatedArticles %}
        {% set relatedArticles = relatedArticles|merge([item]) %}
    {% endif %}
{% endfor %}

But it doesn't remove the duplicates. Adding find() to the queries to turn them in to an array doesn't work either. Any way I can do this?

EDIT: I tried this, too:

{% set relatedArticles = article.relatedArticles.find()|merge(craft.entries.relatedTo(article).find()) %}

Yep, there's a great mystery about how the in containment operator actually works with objects. Twig Docs say it's possible:

You can use this filter to perform a containment test on strings, arrays, or objects implementing the Traversable interface.

but I also tried this (multiple times) and did't get it working. I eventually always ended up using a workaround. In your case I'd do the following and use the entry's ID in the conditional:

{# Get arrays of entries #}
{% set entriesA = craft.entries(paramsA).find() %}
{% set entriesB = craft.entries(paramsB).find() %}

{# Prepare merge #}
{% set entriesBIds = craft.entries(paramsB).ids() %}
{% set allEntries = entriesB %}

{# Merge arrays #}
{% for entry in entriesA %}

    {# Don't merge duplicates #}
    {% if entry.id not in entriesBIds %}
        {% set allEntries = allEntries|merge([entry]) %}
    {% endif %}

{% endfor %}
  • Thanks for this. I ended up doing something very similar. Oct 31 '14 at 13:59
  • 2
    The problem with "in" and objects is that since an object can have an variable depth, how deep does it need to check before deciding if they two objects are equal? Is a "shallow comparison" good enough, where it just compares the properties/methods on the first level, or do you do a much more expensive "deep comparison" and explore the whole object tree before deciding?
    – Brad Bell
    Oct 31 '14 at 17:22

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.