0

I have a Friend class and a Friendship class in Parse.com. Friendship class has 2 columns named "Friend1" and "Friend2" that represent the relationship and are pointers to the "Friend" class.

I want to find my 20 oldest friends. So I'm trying a nested query like so in swift:

var queryInner = PFQuery(className: "Friend")
queryInner.orderByDescending("Age")

var queryOuter = PFQuery(className: "Friendship")
queryOuter.whereKey("Friend2", matchesQuery: queryInner)
queryOuter.whereKey("Friend1", equalTo: PFObject(withoutDataWithClassName:"Friend", objectId: friendId))
queryOuter.includeKey("Friend2")
queryOuter.limit = 20

queryOuter.findObjectsInBackgroundWithBlock{
//handling
}

It retrieves 20 friends, but they are not sorted by descending age. Is this a parse problem? a problem with my query? Thanks!

greg lagagne
  • 21
  • 1
  • 4
  • I believe it's a problem parse, see [this](http://stackoverflow.com/questions/21184263/in-parse-com-cloud-code-how-to-sort-records-by-its-child-table) table, where someone tried to do something similiar. One thing I could suggest is trying to use your innerquery as main query and your outerquery to be the innerquery. From one of the two links: "You can only sort a query based on the properties of the object being queried itself.", so by inversing the way you query, you should be able to orderby age! – Bart de Ruijter Mar 18 '15 at 09:45
  • Yeah, kind of a bummer that its not supported natively. The easy work around is to sort the result yourself after the query completes. – danh Mar 18 '15 at 14:03
  • thanks for the pointers guys. indeed it's a bit disappointing that Parse doesn't do that, while it does so many wonderful things. i'll try a few options and report back here. – greg lagagne Mar 18 '15 at 18:15

1 Answers1

2

So guys, as you said, sorting on nested queries is not supported by Parse. As per your suggestions I see 2 possible alternative approaches:

1/ adding an "Age" field to the Friendship class which refers to the age of Friend2 (the relationship table is unidirectionnal); and just do my query on that class. The "Age" field is updated regularly by a background process. less work at runtime

2/ first, find all friends, then, sort the result. probably more work at runtime when the number of friends grow. not sure by how much exactly. also, I believe that the maximum number of items returned by a single parse query is 1000; so once someone has more friends than that, the extra friends won't be retrieved. not super scalable.

I think i'll end up implementing 1/ , unless some parse pro has some last minute advice! :)

greg lagagne
  • 21
  • 1
  • 4