Bear with me as I am not sure the best way to explain this. But to try and summarise... how can I loop through related entries (locations) inside a a related entries loop (exams -> related to the current entry/page) but ONLY output the locations and ONLY output the unique locations (ie. I don't want it t show location1, location1, location2, location1. I just want it to show location1 and location2 (once - unique). This is where I am at, but not working yet.
Here is a screenshot to try and illstrate:
I only want Bushy to appear once, not 4 times.
So my page is setup like this; First I set the Mock Exams to find all the Mock Exams related to the current entry (page). Like so:
{% set mockExams = craft.entries
.section('mockExams')
.with('location')
.relatedTo({
targetElement: entry,
field: 'mockExamCategory'
})
.all() %}
I am then using this code to list all the mock exams in 2 separate areas on the page. This works fine and as expected.
However, I need to then get all the unique location entries that are related to the mock exams. I took me ages to fathom this out on how to to do this. I only managed with some great support through the Discord channel.
Anyway, the way this was finally achieved was as follows:
{% set uniqueLocations = [] %}
{% set uniqueLocationsIds = [] %}
{% for entry in mockExams %}
{% set locations = craft.entries.section('locations').relatedTo(entry.id).all() %}
{% for location in locations %}
{% if location.id not in uniqueLocationsIds %}
{% set uniqueLocationsIds = uniqueLocationsIds|merge([location.id]) %}
{% set uniqueLocations = uniqueLocations|merge([location]) %}
{% endif %}
{% endfor %}
{% endfor %}
{% for location in uniqueLocations %}
{{ location.title }}<br />
{{ location.address }}
{% endfor %}
I have written this up for reference if anyone else comes across this.
But also for anyone more experienced in Craft - is this the most efficient way or is there a more efficient/streamlined approach?