1

I use a structure section with two levels, parents and children. Is it possible to show related entries of a parent, where only a child of that parent is selected as a related entry?

I did try to solve it like this:

{% set children = entry.children().all() %}
{% set relatedEntries = craft.entries.section('news').relatedTo(children).limit(3)%}

But parents now show all entries, not only the entries that are related to (one of) their children.

I would like to create something like this:

**Structure:**
Parent1
-> Child11
-> Child12
-> Child13
Parent2
-> Child21
-> Child22

**News entry**
-> News1 with related entry Child11

**In the Parent template**
News1 is related to Parent1

2
  • Where do you want to show the related entries, on the parent template? So the entry variable in your code is the parent? And what are the children related to, in which field? On the parent or the child?
    – MoritzLost
    Commented Jul 7, 2023 at 9:08
  • Hi Moritz, Yes the entry variable is the parent (in the parent template). And the children of the parent are selected in the entries of the section 'news'.
    – Marcel
    Commented Jul 7, 2023 at 10:01

1 Answer 1

1

Your code looks correct – this query will match all news that are related to any of the children of the current entry. The only thing that might be causing issues is that it will find all news that are related to any of the children in any field, and regardless of which element is the source of target. You can further limit your query to a specific field and source/target relation like this:

{% set children = entry.children().ids() %}
{% set relatedEntries = craft.entries()
    .section('news')
    .relatedTo({
        targetElement: children,
        field: 'myEntriesField',
    })
    .all()
%}

Replace myEntriesField with the handle of the field in your news section that is used to select the child entries.


Another option to better address this: In Craft 4.4+ entries fields have a 'Maintain Hierarchy' setting. This will cause the field to always select all ancestors of the selected child as well. This way, the parent entry of the selected child entry will always be selected as well, and will be directly related to the news entry. Then you can just filter by news that are related to the current (parent) entry.

2
  • 1
    Thank you very much Moritz, it works now with the addition of a curly bracket at the end of the relatedTo.
    – Marcel
    Commented Jul 7, 2023 at 11:52
  • @Marcel Oops, you're right. Just fixed that.
    – MoritzLost
    Commented Jul 7, 2023 at 12:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.