I started building a list of recursive relations:

We're in a project, we want to check interviews related to that project, see which persons participated in those related interviews, and then build an ordered list of all those persons – without duplicates.

My first approach was to combine two loops:

{% set relatedInterviews = craft.entries.section('interviews').relatedTo(entry).all() %}  
{% if relatedInterviews %}  
{% set interviewedpersons = [] %}
  {% for interview in relatedInterviews %}
    {% set relatedPersons = craft.entries.section('persons').relatedTo(interview).all() %}
    {% for person in relatedPersons %}
      {% set interviewedpersons = interviewedpersons|merge([person]) %}
    {% endfor %} 
  {% endfor %}

  {% for interviewedperson in interviewedpersons %}
    <a href="{{interviewedperson.url}}">{{interviewedperson.firstname}}{{interviewedperson.lastname}}</a>{% if loop.last %}{% else %}, {% endif %}
  {% endfor %}
{% endif %}

In PHP, we would now sort and clear duplicates from interviewedpersons, but I see in twig the array sorting possibilities are a bit reduced, right? Probably because building such a list is already more of a controller than a view / template thing?

So is there a better approach to do this double relation, sorting and avoiding duplicates via Craft's Entrymodel?

What about

{% set relatedPersons = craft.entries.section('persons').relatedTo(craft.entries.section('interviews').relatedTo(entry)).orderBy('lastname asc, firstname asc').all() %}
{% for relatedPerson in relatedPersons %}
   <a href="{{relatedPerson.url}}">{{relatedPerson.firstname}}{{relatedPerson.lastname}}</a>{% if loop.last %}{% else %}, {% endif %}
{% endfor %}

– much better? I'm pleasantly surprised this works. Do I have to check for empty bits, and will duplicates be removed already?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.