Here is my situation: I have a bunch of different series (which are each stored in a channel), and there are a bunch of sermons related to each series.

What I need to do is display the most recent entry of each series. Typically I would do this in a SELECT DISTINCT SQL query; How should I go about doing it in Craft?


If I understand your question and structure correctly, then this might work.

{% entries = craft.entries.section('series').limit(null) %}
{% mostRecentSermons = [] %}

{% for entry in entries %}

    {# retrieve most recent sermon related to series #}
    {% set sermon = craft.entries.section('sermons').relatedTo(entry).order('postDate desc').first %}

    {# merge sermon into mostRecentSermons array #}
    {% set mostRecentSermons = mostRecentSermons|merge([sermon]) %}

{% endfor %}

If you need to worry about duplicates then you can use {% if not sermon in mostRecentSermons %} before merging.

You may also want to wrap this in {% cache %}{% endcache %} tags to improve performance.

  • Perfect, thank you! – Ryan James Mar 28 '15 at 22:39

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.