2
我正在研究如何將子項添加到Realm(Swift)父項,並且我想查詢結果。領域 - 將子項添加到父項,然後在父項上查詢結果
不過,我來了一個崩潰
do {
let realm = try Realm()
try realm.write {
for locomotive in locomotives
{
realm.add(locomotive, update: true)
}
let locomotives = realm.objects(Locomotive.self)
for locomotive in locomotives {
print (locomotive.name)
for _ in stride(from: 0, to: locomotive.qty, by: 1) {
let engine : Engine = Engine.init()
locomotive.engines.append(engine)
}
}
}
} catch let error as NSError {
//TODO: Handle error
print(error.localizedDescription as Any)
}
我想創建一定數量的兒童,將其添加到關係
然後,當我嘗試進行查詢;
let locomotives = realm.objects(Locomotive.self)
print(locomotives.count)
// Find all children that are linked to this specific parent
for loco in locomotives {
let engines = realm.objects(Engine.self).filter("parent == \(loco)")
print("listing engines")
for engine in engines {
print ("engine: \(engine.parent)")
}
}
我的父類是(在其最基本減去任何映射代碼)
class Locomotive: Object, Mappable {
dynamic var engineid: String = ""
var engines = List<Engine>()
}
我的子類是:(在其最基本減去任何映射代碼)
class Engine: Object {
let parent = LinkingObjects(fromType: Locomotive.self, property: "engines")
}
這導致崩潰:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "parent == Locomotive {
我想獲得給定孩子的所有家長姓名列表;通常我會這樣做:
for each child in parent.array
{
print child.parent.name
}
但在領域,我無法訪問父母的名稱。
如何查詢父 - 子關係以及類似的命令(獲取父母的名稱屬性)?
非常感謝