2

The RelatedTo function keeps puzzeling me. I got it working with categories, but now I want to do something in reverse with users. But I don't fully understand the RelatedTo function.

I have a channel called "downloads". I also have some users in the back-end. I have added a custom field to the user section called "selectDownloads". This field is a relatedEntry field where the admin can select entries from the downloads channel. Now I want to list all downloads in my template that the current logged in user may see (so the entries that were selected when creating the user).

I read the docs multiple times allready and with some luck and trial and error I got it working on categories. But there I loop through all my products and relate them to a targetSource which is my category by a field that is part of my products channel. In this case however, I want to loop through all my downloads, related to a field that is part of my users section (instead of my downloads channel). So the relation is different.

A more dummy proof explanation with some examples of the RelatedTo function would be welcome. I never know which elements I should address:

 {% set ingredients = craft.entries.section('ingredients').relatedTo({
     sourceElement: cocktail,
     field: 'ingredients' }) %}

sourceElement or targetElement:

Is this a section or field you have to give in?

field:

Is that a field from the ingredients section or the cocktail section?

1 Answer 1

4

You can just use:

{% for entry in craft.entries.section('downloads').relatedTo(currentUser) %}
    {{ entry.title }}
{% endif %}

This is essentially returning an ElementCriteriaModel of reverse related entries sorted by entry date by default. You can also access the related entries through the field itself:

{% for entry in currentUser.selectDownloads %}
    {{ entry.title }}
{% endif %}

This will loop through the related entries in the order they are sorted in the CP.

But to answer your other questions. sourceElement and targetElement can be elements of any element type: entry, category, asset, user, globalSet, tag, etc are all elements. sourceElement simply refers to which is the source of the relationship; and targetElement is what it's related to. field further specifies that you only want to match a specific field rather than using any relationship defined in any field (if you have 2 or more entries fields defined in a channel that are used for different purposes for example).

1
  • My God. Craft is so wonderfully simple! I always look to far for an answer. Love it! Commented Nov 16, 2014 at 11:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.