[英]Core Data: Matching a combination of multiple items in a to-many relation
EDIT: Forgot to mention that I filter out cards with unwanted colors in Swift code afterwards.编辑:忘了提到我后来在 Swift 代码中过滤掉了带有不需要颜色的卡片。
So, this is yet another question regarding to-many relationships in Core Data and how to write a predicate for it.因此,这是关于 Core Data 中的多对多关系以及如何为其编写谓词的另一个问题。 In short, I'd like to match a combination of multiple items in a to-many relation.
简而言之,我想在一对多关系中匹配多个项目的组合。
Search for cards with black and/or white color, meaning:搜索黑色和/或白色的卡片,意思是:
Best results are (simplified):最佳结果是(简化):
NSPredicate(format: "ANY color == Black") // Only black cards, good
NSPredicate(format: "ANY color == White") // Only white cards, good
NSPredicate(format: "ANY color == Black OR ANY color == White") // Only black AND white cards, bad
There is a very similar post that concerns MySQL here, in case it helps further clarifying the issue:这里有一篇与 MySQL 相关的非常相似的帖子,以防它有助于进一步澄清问题:
SQL: Make colors from color-table searchable SQL:使颜色表中的颜色可搜索
根据@pbasdf的评论,我提出了以下解决方案(在实际代码中使用更好的语法):
// Desired colors let includePredicate = NSPredicate(format: “SUBQUERY(color, $C, $C == 'Black' OR $C == 'White').@count > 0”)
// Undesired colors let excludePredicate = NSPredicate(format: “SUBQUERY(color, $C, $C == 'Green' OR $C == 'Red' OR $C == 'Blue').@count == 0”)
// Combined to one predicate let finalPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [includePredicate, excludePredicate]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.