领域 - 如何获得父子关系中实体所有者的列表?

时间:2017-01-22 10:29:31

标签: swift subquery realm nspredicate

使用Swift Realm,我想从父母的角度来看一个孩子的主人。

简单来说,实体关系可以描述为:

Parent -< Child <- Player

使用给定的Parent,我想获得一个玩家(所有者)列表。

当我尝试查询时,我相信我的查询是错误的;

// 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)")

此测试失败:

XCTAssert(owners.count == 1, "Expected: 1, Found: \(owners.count)")

我希望有1位老板。

但相反,我得到0个拥有者。

我做错了什么?

如何使用NSPredicates和Realm获取给定孩子的所有者列表?

非常感谢

编辑:发现我没有添加任何玩家;添加玩家的摘要版本如上所示

1 个答案:

答案 0 :(得分:1)

我现在已经解决了这个问题。

  1. 没有玩家数据可以追加孩子;我已经在我的xctests
  2. 中解决了这个问题
  3. 执行此操作后,对我的测试进行了一些调整后,查询似乎正在工作,并在我的记录器输出中进行了验证。

        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)
            }
        }
    
  4. 测试通过,通过一些控制台日志,我能够验证我的期望。

    问题已解决。

    关闭。