Custom sortable entries - not working as expexted

I’ve set up a short collection called ‘locations’. I added some entries and activated “Custom sortable entries”. Then I ordered the items and also added a hirarchie.

  • entry1
    • entry2
    • entry3
    • entry4
  • entry5
    • entry6
    • entry…

I fetch the collection in php:
$arrPostList = cockpit(‘collections’)->find(‘locations’, [
‘sort’ => [‘category’ => 1, ‘_o’ => 1],
]);
I expected the result to be like
entry1
entry2
entry3

but what I get is different:
entry2
entry3
entry4
entry1

any ideas or is this kind of sorting not implemented as of now?

Does it work if you don’t sort by category or if you inverse '_o' => -1?

If your example’s content is

  • entry2 - category: “a”, _o: 1, _pid: “parent_id”
  • entry3 - category: “a”, _o: 2, _pid: “parent_id”
  • entry4 - category: “a”, _o: 3, _pid: “parent_id”
  • entry1 - category: “b”, _o: 1, _pid: null

than the sorted result looks correct.

I can’t tell much about the hierarchical sorting, because I didn’t really use it in the past.

I changed the code a litle.
2019-09-16%2012_27_36-Window

Result from the following code works as expected:
$arrPostList = cockpit(‘collections’)->find(‘test’, [
‘sort’ => [’_o’ => 1]
]);
but hierarchical sorting doesn’t
2019-09-16%2012_30_12-Window

entry1
#0

entry2
#0

entry4
#0

entry3
#2

OK, I see the problem and I’m not sure, if I can help you.

Nesting entries works with adding a numeric key _o, that starts with 0 in each nesting stage and a parent key _pid with the parent _id key. So entry1, entry2 and entry4 have _o = 0, entry3 has _o = 1. So the sorting works correct with the underlying logic.

I don’t see a useful generic solution to this, because everyone might expect different results when sorting hierachical entries.

If you look at the api controller, hierarchical entries are converted to a tree before sending the output, but only if they aren’t sorted:

You could do the sorting yourself after you get the result from the database or you could think about restructuring your data, e. g. into multiple collections with collection-links…