所以我试图在Realm中使用LinkingObjects,并且似乎在第一级获得了不好的结果(链接不起作用)。
我将在这里添加所有代码。显然不希望人们重复这一切,只是想表明我已经浏览了目前在Stack Overflow中看到的所有答案。
class Book: Object {
@objc dynamic var bookId = 0
@objc dynamic var bookName = ""
var sections = List<Section>()
override static func primaryKey() -> String? {
return "bookId"
}
}
class Section: Object {
@objc dynamic var sectionId = 0
@objc dynamic var sectionName = ""
let chapters = List<RChapter>()
let book = LinkingObjects(fromType: Book.self, property: "sections")
override static func primaryKey() -> String? {
return "sectionId"
}
}
class RChapter: Object {
@objc dynamic var chapterId = 0
@objc dynamic var chapterName = ""
var section = LinkingObjects(fromType: Section.self, property: "chapters")
override static func primaryKey() -> String? {
return "chapterId"
}
}
class DataBase {
static func getChapterById(id: String) -> RChapter? {
let realm = try! Realm()
let chapter = realm.objects(RChapter.self).filter("chapterId = \(id)").first
return chapter
}
static func writeToRealm(json: JSON) {
let book = Book()
book.bookId = json["bookId"].int!
book.bookName = json["bookName"].string!
let section = Section()
section.sectionId = json["sectionId"].int!
section.sectionName = json["sectionName"].string!
let chapter = RChapter()
chapter.chapterId = json["chapterId"].int!
section.chapters.append(chapter)
book.sections.append(section)
let realm = try! Realm()
try! realm.write {
realm.add(book, update: true)
}
}
}
但是在填满数据库后,我无法从章节中获得部分。
谁知道为什么? 谢谢,