cardigan cardigan - 4 months ago 19
Swift Question

Realm - Get a list of all parents of all children from the child point of view

In a game I am writing using Realm and Swift I'm trying to do this relationship;

Locomotive -> Engine <- Player



  • A
    Player
    has many
    Engines

  • A
    Locomotive
    has many
    Engines



As a sidenote, A player can only ever own one engine (child) from one locomotive (parent).

I'm wanting to get a list of all parents of all children that a player owns using Realm and NSPredicates.

That is to say, given a player entity; list all parents of all the engines that a player owns and sort the parent objects by cost.

As the app doesn't know directly which player owns what locomotive, I'd like to do a query on the engines that a player owns to find out what locomotive they own.

I feel its a bit overkill to have 2 relationships in the locomotive entity (one for all the engines, and one for all the players) when that information can be garned through its child object(s).

Specifically, I want a list of all locomotives that a player owns, sorted by cost through the engines entity. (I hope this makes sense)

The relevant code from my project is as follows;

// Locomotive entity

public class Locomotive: Object {
var engines = List<Engine>()
private(set) dynamic var cost: Int = 0
}

// Engine entity

public class Engine: Object {
private let parents = LinkingObjects(fromType: Locomotive.self, property: "engines")
private let owners = LinkingObjects(fromType: Player.self, property: "engines")

}

// Player entity

public class Player: Object {
public let engines = List<Engine>()
}

// Give me a list of all locomotives I own through the engines entity
// and sort the locomotives by cost

let predicate = NSPredicate(format: "ANY engines.owners == %@", firstPlayer)

let allLocos = realm.objects(Player.self)
.filter(predicate)

print (allLocos.count)


Whilst this gives me a list of all engines where the player owns, it doesn't give me the list of locomotives (or sorted by cost)

Thus my query is:

How do I grab a list of all parents (locomotives) from all children that the player owns and ensure that the sort order is by cost?

I am hopeful that I have explained my issue correctly and welcome any help and assistance that may result from my query.

Thanks

TiM TiM
Answer Source

If I read that right, given a Player object, you want to retrieve a list of the Locomotive objects that are the parents of the Engine objects that are children of that Player object.

You should be able to do a lookup against the Locomotive object using the Player object's engines property. It would look something like this (Although admittedly, this is untested):

let player = // Get the player
let locomotives = realm.objects(Locomotive.self).filter("ANY self IN %@", player.engines)