在境界中查询

时间:2016-06-20 08:15:48

标签: ios swift realm

我有一个表主题,成绩,章节和问题的数据库。一个主题有很多年级,一个年级和很多章,一章有很多问题。如果我想执行搜索主题=生物学,年级= 4,章节= 1的所有问题,我应该如何构建查询?

我的课程

class Subject:Object {
    dynamic var subject_id = 0
    dynamic var subject_name = ""
    let grades = List<Grade>()
    override static func primaryKey() -> String? {
        return "subject_id"
    }
}

class Grade:Object {
    dynamic var grade_id = 0
    dynamic var grade_num = 0
    let chapters = List<Chapter>()
    override static func primaryKey() -> String? {
        return "grade_id"
    }
}

class Chapter:Object {
    dynamic var chapter_id = 0
    dynamic var chapter_num = 0
    let questions = List<Question>()

    override static func primaryKey() -> String? {
        return "chapter_id"
    }
}

class Question:Object {
    dynamic var question_id = 0
    dynamic var question_desc = ""
    dynamic var question_ans = ""

    override static func primaryKey() -> String? {
        return "question_id"
    }
}  

到目前为止,我能想到实现这一目标的唯一方法如下,我觉得有很多嵌套循环的方法,如果没有。

let realm = try! Realm()
let subjects = realm.objects(Subject).filter(NSPredicate(format: "subject_name = %@", "Biology"))

var searched:List<Question>?

for subject in subjects {
    if subject.subject_name == "Biology" {
        for grade in subject.grades {
            if grade.grade_num == 4 {
                for chapter in grade.chapters {
                    if chapter.chapter_num == 1 {
                        searched = chapter.questions
                    }
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在Realm 0.100之后,可以在查询中使用反向关系。

所以,我的建议是在你的模型中添加反向关系,如下所示:

class Grade:Object {
    dynamic var grade_id = 0
    dynamic var grade_num = 0
    let chapters = List<Chapter>()

    let subjects = LinkingObjects(fromType: Subject.self, property: "grades")

    override static func primaryKey() -> String? {
        return "grade_id"
    }
}

class Chapter:Object {
    dynamic var subject_id = 0
    dynamic var chapter_num = 0
    let questions = List<Question>()

    let grades = LinkingObjects(fromType: Grade.self, property: "chapters")

    override static func primaryKey() -> String? {
        return "subject_id"
    }
}

class Question:Object {
    dynamic var question_id = 0
    dynamic var question_desc = ""
    dynamic var question_ans = ""

    let chapters = LinkingObjects(fromType: Chapter.self, property: "questions")

    override static func primaryKey() -> String? {
        return "question_id"
    }
}

然后您可以查询与此类似的模型:

let questionsIWant = realm.objects(Question.self)
    .filter("ANY chapters.chapter_num == 3")
    .filter("ANY chapters.grades.grade_num == 1")
    .filter("ANY chapters.grades.subjects.subject_name == 'Biology'")