Reverse relationships with entries and users I have a relationship between users and 'locations', and I'm using the code below to output some markers for a map.

This all works fine except for two things:


I'm repeating a couple of 'for' loops. When I try not to repeat
them, the 'markers' and 'markerInfo' return 'undefined'.
Within markerInfo, I'd like to list the names (e.g. 'user.firstName') of the users related to that location, but when I try, I get a list of ALL users that have a relationship with ANY location.


In plain language, what I'm trying to do is:


Find me all the users who are part of the 'family' group.
Find me all the locations which are related to those users and plot each
one (but only once for each location).
For each location, give me a list of the users that have a relationship with it.


--


My source elements are entries in the section 'locations', with the
field 'relatedPeople'. 
My target elements are 'users' (from the group
'family').


How can I make this more performant (not repeat things), and get a list of users per location within 'markerInfo'?

{% set people = craft.users.group('family') %}

{% set markers %}
    {%- for person in people.all() -%}
        {% set relatedPlaces = craft.entries.section('locations').relatedTo({
            targetElement: person,
            field: 'relatedPeople'
        }) %}
        {%- for place in relatedPlaces.all() -%}
        ['{{ place.location.address }}', {{ place.location.lat }},{{ place.location.lng }}],
        {%- endfor -%}
    {%- endfor -%}
{% endset %}

{% set markerInfo %}    
    {%- for person in people.all() -%}
        {% set relatedPlaces = craft.entries.section('locations').relatedTo({
            targetElement: person,
            field: 'relatedPeople'
        }) %}
        {%- for place in relatedPlaces.all() -%}
        ['&lt;div class="info_content"&gt;' + '&lt;h5&gt;{{ place.title|e('js') }}&lt;/h5&gt;' + '{% if place.startDate|length %}{{ place.startDate | date('M Y') }}{% endif %}{% if place.startDate|length and place.finishDate|length%} to {% endif %}{% if place.finishDate|length %}{{ place.finishDate | date('M Y') }}{% endif %}' + '&lt;/div&gt;'],
        {%- endfor -%}
    {%- endfor -%}
{% endset %}
{% set people = craft.users.group('family').ids() %}
{% set relatedPlaces = craft.entries.section('locations').relatedTo({
    targetElement: person,
    field: 'relatedPeople'
}) %}


Grab all the ids from your users, then find all locations related to those. This way you don't need multiple loops and get each location once and not multiple times