简体   繁体   English

核心数据:匹配一对多关系中的多个项目的组合

[英]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.简而言之,我想在一对多关系中匹配多个项目的组合。

Setup设置

  1. Color table with five colors: Red, Green, White, Black, Blue五种颜色的颜色表:红、绿、白、黑、蓝
  2. Card table , each card has a to-many relation to color table卡片表,每张卡片与颜色表有一对多的关系

Goal目标

Search for cards with black and/or white color, meaning:搜索黑色和/或白色的卡片,意思是:

  1. Card may be black only卡片可能只有黑色
  2. Card may be white only卡片可能只有白色
  3. Card may be both black and white卡片可以是黑白的

So far迄今为止

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM