我是Realm的新手,并且查询问题会让我疯狂几天。我有2个简单的类Dog和Person as:
class Dog: Object {
dynamic var dogName = ""
dynamic var dogAge = 1
var owners: [Person] {
return linkingObjects(Person.self, forProperty: "dogs")
}
}
class Person: Object {
dynamic var firstName = ""
let dogs = List<Dog>()
}
向Realm添加数据后,我有以下数据:
的
let database = try! Realm()
// Query all Dogs- It should have 7 dogs
let allDogs = database.objects(Dog)
print("A total of \(allDogs.count) dogs") // 7 dogs - correct
// Query All dogs between age of 4 and 12 - there should be 5 dogs
let agedDogs = database.objects(Dog).filter("dogAge BETWEEN {4,12}")
print("Dogs between Age 4 and 12 = \(agedDogs.count) \n") // 5 dogs - OK
我想知道所有agedDog
,其中有多少属于奥斯卡?
我试过了:
let specificOwnerAgedDogs = agedDogs.filter("ANY owners.firstName = 'Oscar'")
print("Oscar Dogs between Age 4 and 12 = \(specificOwnerAgedDogs)")
但是此查询会导致错误:
由于未捕获的异常“无效的属性名称”而终止应用,原因:在“狗”类型的对象中找不到“属性”所有者
我正在使用Realm Swift和Swift 2.1.1。
答案 0 :(得分:1)
Realm Swift does not yet support provide direct support for queries that traverse inverse relationships,例如owners
类的Dog
属性。这是我们正在努力的事情,它应该在不久的将来成为Realm Swift版本。
目前,您可以通过在Swift中执行某些过滤而不是在谓词中来解决此限制:
let specificOwners = database.objects(Person).filter("firstName = 'Oscar'")
let specificOwnerAgedDogs = specificOwners.flatMap() { owner in
owner.dogs.filter() { $0.dogAge >= 4 && $0.dogAge <= 12 }
}
答案 1 :(得分:0)
let noOwn = agedDogs.flatMap {
(ndog) -> Dog? in
ndog.owners == [] ? ndog : nil
}
我使用此代码查找没有任何所有者的所有oldDogs的列表? 有没有想过这个?