2

I want to sort (and paginate) entries from a structure section based on the number of descendants. This is the effective criteria I want to query:

craft.entries.section('myStructure').level(1).order('descendants desc')

Since getDescendants.count() is not a number stored against each entry in the database (AFAIK), how does one go about getting this result?

1 Answer 1

2

You could use a Preparse field to calculate and store that value.

The only downside is, it'll only do that calculation when you save the parent entry. So if you add another descendant, you'd have to go back and re-save the parent entry to re-calculate the value.

Pro tip: You can go to Settings > Sections and re-save the section you are working with. This will automatically trigger a re-save of every single entry in that section.

4
  • I'd like to upvote with half a point for this half baked solution. But as it's probably the only way to approach that problem without custom sql, I'll give you the full upvote. :)
    – carlcs
    Mar 31, 2016 at 21:33
  • Lol, thanks @carlcs. It's the only way I could think of without introducing something like template hooks.
    – Lindsey D
    Mar 31, 2016 at 21:37
  • I did come across the Preparse Field plugin while searching for a solution. Since I want this process to be automated, I’m guessing my best bet it to write a custom plugin where I latch on to a hook and trigger a re-save on the parent everytime an entry is modified in that section.
    – rungta
    Apr 1, 2016 at 18:22
  • @rungta: That sounds like a good solution!
    – Lindsey D
    Apr 1, 2016 at 19:51

Your Answer

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

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