【问题标题】:Core Data: Matching a combination of multiple items in a to-many relation核心数据:在一对多关系中匹配多个项目的组合
【发布时间】:2024-05-21 11:10:01
【问题描述】:

编辑:忘了提我后来在 Swift 代码中过滤掉了带有不需要颜色的卡片。

所以,这是另一个关于 Core Data 中的多对多关系以及如何为其编写谓词的问题。简而言之,我想在一对多关系中匹配多个项目的组合。

设置

  1. 颜色表有五种颜色:红、绿、白、黑、蓝
  2. 卡片表,每张卡片与颜色表有一对多的关系

目标

搜索黑色和/或白色的卡片,意思是:

  1. 卡片可能只有黑色
  2. 卡片可能只有白色
  3. 卡片可能黑白两色

到目前为止

最好的结果是(简化的):

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

这里有一篇关于 MySQL 的非常相似的帖子,以防它有助于进一步澄清问题:

SQL: Make colors from color-table searchable

【问题讨论】:

  • NSPredicate(format: "color IN %@, ["Black", "White"])?
  • 也试过IN,没有区别。 ://
  • 卡片实体中有多少个对象?
  • 大约。 15 000 - 20 000 个对象。
  • NSPredicate(格式:“SUBQUERY(color, $C, $C == Black OR $C == White).@count > 0”)

标签: ios swift core-data nspredicate


【解决方案1】:

根据@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]

【讨论】:

    最近更新 更多