I want to do exactly this: Multi-step & 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()
.relatedTo({ targetElement: publisher, field: 'publisher' })
.ids() %}

{% set authors = craft.entries()
.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'?

  • Search your logs (craft/storage/runtime/logs/craft.log, etc.) for the error message you’re getting. Can you post the stack trace that gets logged with it? – Brandon Kelly Oct 17 '17 at 10:42
  • Yes you’re right, field: 'books' should have been field: 'author'. Just updated the GH issue. – Brandon Kelly Oct 17 '17 at 10:46
  • Thank you Brandon, here's the log: textuploader.com/d4uuk – Rivu Meyano Oct 17 '17 at 12:30

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()
        .relatedTo({ sourceElement: bookIds, field: 'books' })
        .all() %}
{% else %}
    {% set authors = [] %}
{% endif %}
  • Thanks very much Brandon, but it appears to be giving the same error: textuploader.com/d4uwl – Rivu Meyano Oct 17 '17 at 15:36
  • @RivuMeyano What does {{ dump(bookIds) }} output for you? – Brandon Kelly Oct 17 '17 at 15:38
  • If I only include that in my template, then I get and "Unknown "dump" function" error, but I guess that's because bookIds hasn't been defined. It appears to be the first block of code that gives the "Undefined offset: 0" error, but if I include that in order to have the Dump function do something, I will of course still get the "Undefined offset: 0" error. – Rivu Meyano Oct 17 '17 at 16:01
  • Sorry, you should enable Dev Mode first. (Set 'devMode' => true in craft/config/general.php.) And you should put that tag after the {% set bookIds = ... %} tag, but remove the author code after it. – Brandon Kelly Oct 17 '17 at 16:02
  • Ah - here's what Dump gives me: pictr.com/image/UwhxP – Rivu Meyano Oct 17 '17 at 16:06

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.