Filtering by cousins I want to do exactly this: Multi-step &amp; bi-directional relations with relatedTo (#1640)


  Common example: Let’s say you have Books, Authors, and Publishers, and two relationship fields on the Books channel: author and publisher. On a Publisher’s page, you want to list all of the Authors that have published books with them.


Here’s what I’ve tried:

{% set bookIds = craft.entries()
.section('books')
.relatedTo({ targetElement: publisher, field: 'publisher' })
.ids() %}

{% set authors = craft.entries()
.section('authors')
.relatedTo({ sourceElement: bookIds, field: 'books' })
.all() %}


However the code results in an "Undefined offset: 0" error. The error seems to occur in the first block of code.

Additionally, I'm not sure about the field in the penultimate line, shouldn't it be 'authors' rather than 'books'?
The error you’re getting is a bug in Craft. (Just fixed that for the next release.)

To work around it, replace the {% set authors ... %} tag with:



{% if bookIds|length %}
    {% set authors = craft.entries()
        .section('authors')
        .relatedTo({ sourceElement: bookIds, field: 'books' })
        .all() %}
{% else %}
    {% set authors = [] %}
{% endif %}