ios - How can I call aggregate functions for properties of relationships in Realm? -
is there way use aggregate functions properties in one-to-one , one-to-many relationship? here's simple example of structure i'm using:
class toy: object { dynamic var purchasedate: nsdate? dynamic var name: string = "" let ratings = list<rating>() dynamic var toyowner: person? } class rating: object { var stars: int = 0 var comments: string? } class person: object { dynamic var name: string = "" dynamic var age: int = 0 } i'd along lines of this:
// average age of owner of toys purchased within date range let avgage: double = realm.objects(toy) .filter("purchasedate >= %@ && purchasedate <= %@", startdate, enddate) .avg("person.age") // sum stars given toys purchased within date range let totalstars: double = realm.objects(toy) .filter("purchasedate >= %@ && purchasedate <= %@", startdate, enddate) .sum("sum(ratings.stars)") is there way these aggregate functions within realm?
although realm have aggregate value functions (see aggregate operations docs on realmcollectiontype), don't work multi-level keypaths person.age.
however, can of heavy lifting realm modifying queries:
// average age of owner of toys purchased within date range let ages = realm.objects(toy) .filter("purchasedate between %@", [startdate, enddate]) .valueforkeypath("toyowner.age") as! [double] let avgage = ages.reduce(0, combine: +) / double(max(ages.count, 1)) // sum stars given toys purchased within date range let totalstars = realm.objects(toy) .filter("purchasedate between %@", [startdate, enddate]) .reduce(0) { sum, toy in return sum + toy.ratings.sum("stars") }
Comments
Post a Comment