0

我有一个模型类别,其关系属性文章是一个 NSOrderedSet。现在我想获取满足特定条件的文章的所有类别,在 SQL 中我会写:

SELECT * 
FROM Category AS cat
JOIN Article AS art ON art.categoryId = cat.categoryId AND art.gender='m';

我试过:

NSPredicate(format: "articles.gender like %@ OR articles.gender = %@", gender.lowercased(), "n")

我收到以下错误:

*** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“此处不允许使用多对多键”

完整代码:

    let ctx = self.Context()

    var gender = UserDefaults.standard.string(forKey: "gender_preference") ?? "*"
    if gender.uppercased() == "N" { gender = "*" }

    // Create Fetch Request
    let fetchRequest: NSFetchRequest = ArticleCategory.fetchRequest()
    let predicate = NSPredicate(format: "articles.gender like %@ or articles.gender = %@", gender, "n")
    fetchRequest.predicate = predicate

    // sort by name
    let sort = NSSortDescriptor(key: "name", ascending: true)
    fetchRequest.sortDescriptors = [sort]

    do {

        let result = try ctx.fetch(fetchRequest)
        return result

    } catch {

        print(error)

    }

    return []

亲切的问候

编辑:

模型 关系

4

1 回答 1

0

我发现使用 SUBQUERY 比使用 ANY、ALL、NONE 或 SOME 更可靠,尤其是复合子句。如果满足条件的文章数大于零,则获取其任何文章满足条件的类别等效于获取:

let predicate = NSPredicate(format: "SUBQUERY(articles, $a, $a.gender like %@ OR $a.gender == %@).@count > 0", gender, "n")
于 2017-04-12T21:20:46.310 回答