Using Swift Realm, I'm wanting to get of owners of a child from the viewpoint of the parent.
In simple terms, the entity relationship can be described as:
Parent -< Child <- Player
Using a given Parent, I want to get a list of Players (owners).
I believe my query is wrong, when I try my query;
// Cut-down summary of Realm objects and relationships
public class Parent: Object {
var children = List<Child>()
}
public class Child: Object {
private let parents = LinkingObjects(fromType: Parent.self, property: "children")
private let owners = LinkingObjects(fromType: Player.self, property: "children")
var parent:Parent? {
return self.parents.first
}
var owner: Player? {
return self.owners.first
}
}
public class Player : Object {
public let children = List<Child>()
}
let realm = try! Realm()
self.createPlayers(amount: 5)
let playerList = realm.objects(EYPlayer.self)
XCTAssert(playerList.count == 5)
// In my tests:
let firstParent = realm.objects(Parent.self).first
let firstChild = firstParent?.children.first
let firstPlayer = realm.objects(Player.self).first
// Assign the first player with the first child
try! realm.write {
firstPlayer?.children.append(firstChild!)
}
// give me a list of owners for a given parent
let owners = realm.objects(Parent.self).filter("ANY children.owners.@count > 0")
print (owners)
// Test fails; it says there are 0 results
XCTAssert(owners.count == 1, "Expected: 1, Found: \(owners.count)")
This test fails:
XCTAssert(owners.count == 1, "Expected: 1, Found: \(owners.count)")
I expect there to be 1 owner.
But instead, I get 0 owners.
What am I doing wrong?
How can I get a list of owners of a given child using NSPredicates and Realm?
Many thanks
Edit: Found that i wasn't adding any players; a summarized version of adding players is shown above
I have now solved the issue.
After I did this, and a few adjustments to my tests, the queries appear to be working and verified it in my logger output.
let firstParent = realm.objects(Parent.self).first
let firstPlayer = realm.objects(Player.self).first
let firstChild = firstParent?.children.first
XCTAssert(firstChild?.parent == firstParent)
try! realm.write {
firstPlayer!.children.append(firstChild!)
}
let listOfChildren = realm.objects(Parent.self).filter("ANY children.owners.@count > 0")
XCTAssert(listOfChildren.count == 1)
XCTAssert(firstPlayer?.children.count == 1)
for child in listOfChildren {
for (index, eng) in child.children.enumerated() {
if (index == 0) {
XCTAssert(eng.owner != nil)
}
XCTAssert(child.parent == loco)
}
}
The tests pass, and through some console logs I was able to verify my expectations.
Issue is resolved.
Closed.