2

I'm sure this must be simple but I've tried multiple options with little success. What is the best way to build a query to get the children of more than one entry via an entry field?

For one parent would be:

{% set parent = craft.entries.id(parent_id).one() %}
{% for child in parent.children.all() %}
//Stuff
{% endfor %}

But I cant work out how to build the initial query to include more than one parent entry. The output I am looking for is a query that allows me to loop through all of the children from both(or more) entries selected. eg:

{% set query = craft.entries.id([4,35]).all().children.all() %}

Any help much appreciated!

2 Answers 2

2

There's a method available to all element queries called getDescendants() (or like any method in Yii you can omit the get prefix and use descendants()):

{% for child in craft.entries.id([4,35]).descendants().all() %}
    <pre>{{ dump(child.title) }}</pre>
{% endfor %}

You can also pass in a distance integer if you want to limit to direct children/grandchildren.

https://craftcms.com/docs/4.x/elements.html#methods

5
  • This is exactly what I was looking for! Thank you :) Jun 5, 2023 at 9:10
  • Although saying that having just tried this it only returns the parent entry...no child entries are output using the above... Jun 5, 2023 at 15:26
  • hm, I tested this and it worked ok for me. What version of Craft are you using? Jun 5, 2023 at 15:34
  • Craft version: Craft Pro 4.4.13 Have tried a variety of things and can only return the parent entry. Interestingly looking through the docs and trying getAncestors() returns an error: Calling unknown method: craft\elements\db\EntryQuery::getAncestors() Jun 7, 2023 at 8:54
  • Are all of the entries you're querying part of a Craft Structure? Those methods are only available to such elements. Jun 7, 2023 at 10:25
1

Why don't you get the children from each entry individually and then merge them together like so:

{% set childrenOne = craft.entries.id(entryID).one().children.all() %}
{% set childrenTwo = craft.entries.id(entryID).one().children.all() %}

{% set allChildren = childrenOne|merge(childrenTwo) %}
1
  • Beware that pretty much every time you write .one() or .all(), you are executing DB queries... and fairly heavy ones in the case of element queries. So I wouldn't recommend this way. You could mitigate slightly by eager loading the children: craft.entries.id(entryID).with('children').one(), but still not great. Jun 3, 2023 at 8:38

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.