I have a channel with a related users field. I want to output all channel entries ordered by the number of related users, this is what i have so far:

    set entries = craft.entries.find({
        section:  'MyChannel',
        orderBy:  'relatedUsers'

What do i do to order by the number of related users?


Any native solution is likely to be slow - I would recommend using the Preparse field plugin.

It lets you use Twig to dynamically generate a field at the time an entry is saved — you could have Preparse count up the number of related users on save, and then sort by that custom field.

  • Thanks. I ended up creating a count field which i update when new users are related.
    – BillyMedia
    Apr 8 '16 at 12:46
  • Did you do it with Preparse? I'd recommend that over a manual text field, as the Preparse field will always recalculate based on the number of relations. The code would be as simple as: {{ entry.myRelatedUsersField|length }} Apr 8 '16 at 13:30
  • I read that preparse updates on entry updates, which wont work in this case as its a hidden channel storing data from an api which is populated via a custom plugin. So I added the field update to the plugin.
    – BillyMedia
    Apr 8 '16 at 15:28
  • I believe it runs any time onSaveEntry fires, so if the custom plugin is firing the EntryModel's saveEntry method, it should run. That being said, it sounds like your way will work without issue. Apr 8 '16 at 15:49

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.