Assume I have the following schema:
var Car = {
id: 'int',
make: 'string',
model: 'string',
};
var Person = {
id: 'int',
first_name: 'string',
last_name: 'string',
};
var Passenger = {
id: 'int',
person: {type: 'Person'},
car: {type: 'Car'},
};
If I do the following, I get the error Property 'person.last_name' does not exist on object type 'Passenger'.
realm.objects('Passenger').sorted('person.last_name')
Is my syntax incorrect, or is sorting by sub-objects not supported? If it's not supported, are there plans to support it?
This is not currently support, but it's a great feature suggestion! For now, you can use Array.prototype.sort to do this manually. Something like this should work:
let passengers = realm.objects('Passenger').slice();
passengers.sort((a, b) => a.person.last_name.localeCompare(b.person.last_name));
@appden Thanks for the suggestion. My understanding is by keeping the objects wrapped in Results, any relevant database writes would get persisted to the result set. If I call slice(), I lose that ability, correct?
My thought was instead adding a last_name to the Passenger class, which would be sync'd manually by me with the underlying Person. I could then called sorted(last_name) on Passenger to achieve the same result while maintaining the Results object ability to auto-update.
Your solution sounds like it will work. We eventually will add support for custom sort functions but it will be a while before we have time to build it.
Hey @alazier, when you say 'a while', do you have an ETA? Would be very valuable to be able to sort by a property of a child object.
@edmofro this wont happen until there is core support and I don't think that is on the near term roadmap. In the meantime you can use the workaround mentioned here https://github.com/realm/realm-js/issues/437#issuecomment-219551900
Support for this was added to core in realm/realm-core#1969 / realm/realm-core#2011.
@bdash is this support available for the react native too ?? I started with realm for react native 3-4 days back but sorting based on nested keys doesnt seem to work
This issue tracks exposing core's support to React Native and Node.
Is it going to be added to RN too? I'm trying with latest version and does not work :/
It will be added but isn't yet. This issue is for keeping track of it.
This has been implemented for a while (#1303) but for some reason this issue wasn't automatically closed.
Most helpful comment
It will be added but isn't yet. This issue is for keeping track of it.