2

I have channel X set up where it's entries have a "users field", an "entries field" (that are picked from channel Y) and a whole bunch of other data with regards to the how a defined user has interacted with the defined entry.

Whilst viewing an entry from channel Y I wish to dig into the data kept in channel X, more specifically the entry in channel X that has both the same users field as the currentUser AND the same entries field as the entry viewed.

My current solution is the following and makes me cringe with the thought of things getting bigger...

{% set fetchedResults = craft.entries.section('channelXhandle').relatedTo(currentUser) %}
{% for resultEntry in fetchedResults %}
    {% if resultEntry.member.first().id == currentUser.id %}
        {# grab the fruit #}
    {% endif %}
{% endfor %}

It's done the trick up until now, but now I want to find out if there is an entry in channel X that has both the channel Y entry and currentUser defined together.

I've tried the following but it didn't help. It retrieves all the entries as though the relatedTo params are currentUser or entry rather than currentUser and entry that I'm looking to retrieve.

{% set fetchedResults = craft.entries.section('channelXhandle').relatedTo(currentUser, entry) %}

Any pointers in the right direction much appreciated!

Solution in light of Steve's Answer

{% set fetchedResult = craft.entries.section('channelXhandle').relatedTo('and',
    { sourceElement: currentUser, field: '[users field handle]' },
    { targetElement: entry, field: '[entries field handle]' }
).first() %}

Note, I tagged on .first() in the above since in my case there should only be one resulting match anyway.

1

If you take a look at the Relations page from the docs. The last example at the bottom of the page shows how you can do a query using AND for multiple criteria.

The example from the page:

Passing Multiple Relation Criteria

There might be times when you need to factor multiple types of relations into the mix. For example, outputting all of the current user’s favorite cocktails that include Gin:

{% set gin = craft.entries.section('ingredients').slug('gin').first() %}

{% set cocktails = craft.entries.section('cocktails').relatedTo('and',
    { sourceElement: currentUser, field: 'favoriteCocktails' },
    { targetElement: gin, field: 'ingredients' }
) %}

That first argument ('and') specified that all of the relation criteria must be matched. You can pass 'or' instead if you want any of the relation criteria to match.

Hopefully that'll point you in the right direction.

  • 1
    Great thanks Steve! In light of this I've edited my question with the answer. – Dazza Aug 8 '17 at 8:23

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.