GoNinja GoNinja - 1 month ago 13x
Swift Question

Realm query nested object

Hello everyone I'm having difficulties archiving one thing with a query of nested object. I have two realm object Championship and Game.

class Championship: Object {
dynamic var id: Int = 0
dynamic var name: String = ""
let games = List<Game>

override static func primaryKey() -> String? {
return "id"


class Game: Object {
dynamic var id: Int = 0
dynamic var homeTeamName: String = ""
dynamic var awayTeamName: String = ""
dynamic var status: String = "" //"inprogress", "finished", "scheduled"

override static func primaryKey() -> String? {
return "id"


And basically I want to retrieve all championships that have games with status "inprogress", so what I'm doing to archive that is:

let realm = try! Realm()
realm.objects(Championship.self).filter("ANY games.status = 'inprogress'")

What that query is doing is giving me all championships that have at least one game with that status, but is also giving me all the the games from that championship, but actually I just want the games with "inprogress" status.

There any way for doing that?


You could take two approaches here. If you want all games with inprogress status, you could write this:

let inProgressGames = realm.objects(Championship.self)
                           .flatMap { $0.games }
                           .filter { $0.status == "inprogress" }

This will return you all games in progress inside [Game] array. flatMap is used to combine all games from all championships and filter is used to filter all games with inProgress status.

If you want championships where every game is inprogress you could write:

let inProgressChampionships = realm.objects(Championship.self).filter {
   let inProgressGames = $0.games.filter { $0.status == "inprogress"}
   return $0.games.count == inProgressGames.count

This will return array of Championship where each game is inprogress.

Other that that, I would recommend using enum for game status instead of hard-coded strings.