查询域时如何避免“包含数组属性的键路径必须使用聚合操作”异常?

时间:2017-06-08 05:09:25

标签: swift realm

我有一个具有以下结构的Realm对象数据库:

class ItemModel: Object {
    dynamic var id: Int = 0
    dynamic var catId: Int = 0
    dynamic var subId: Int = 0
    dynamic var itemName: String = ""
    dynamic var sortOrder: Int = 0
    dynamic var favorite: Bool = false

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

class SubCategoryModel: Object {
    dynamic var id: Int = 0
    dynamic var catId: Int = 0
    dynamic var subCatName: String = ""
    dynamic var desc: String = ""
    dynamic var sortOrder: Int = 0
    let haveUnit = List<ItemModel>()

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

class CategoryModel: Object {
    dynamic var id: Int = 0
    dynamic var catName: String = ""
    dynamic var sortOrder: Int = 0

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

要查询数据库,我使用以下代码:

var data = List<ItemModel>()
let index = indexPath.section
var query = "catId == \(inCategory)"
if (searchTextValue != "") {
    query += " AND itemName CONTAINS[c] \(searchTextValue)"
}
if index == 0 {
    let unitFavorite = DBManager.realm.objects(ItemModel.self).filter("\(query) AND favorite == true")
    data += unitFavorite
} else {
    var subquery = "catId == \(inCategory)"
    if (searchTextValue != "") {
        subquery += " AND ANY haveUnit.itemName CONTAINS[c] %@"
        let subCat = DBManager.realm.objects(SubCategoryModel.self).filter(subquery, searchTextValue).sorted(byKeyPath: "sortOrder", ascending: true)
        data += subCat[indexPath.section - 1].haveUnit
    } else {
        let subCat = DBManager.realm.objects(SubCategoryModel.self).filter(subquery).sorted(byKeyPath: "sortOrder", ascending: true)
        data += subCat[indexPath.section - 1].haveUnit
    }
}

运行此代码时,我总是看到以下异常:

  

由于未捕获的异常终止应用程序'无效谓词',原因:'包含数组属性的关键路径必须使用聚合操作'

你能帮我理解为什么我会看到这个例外以及我能做些什么来避免它?

0 个答案:

没有答案