Many to many relationship core data query for specific collection

让人想犯罪 __ 提交于 2020-02-04 05:26:26

问题


public enum Ability: String {
  case newcomer = "Newcomer"
  case beginner = "Beginner"
  case intermediate = "Intermediate"
  case advanced = "Advanced"
}

public enum Group: String {
  case solo = "Solo"
  case duo = "Duo"
  case team = "Team"
}

I want to find all performances that match the following.

ability == "Beginner"
group == "Duo"
performers == "Jane Davies" && "Alice Evans"

The documentation suggests that aggregate operations in core data are not supported, which is surprising. Questions like this have been asked before here and suggest the use of 'Any'.

To my understanding, 'Any' would return performances that include 'Jane' or 'Alice' or 'Jane & Alice' right? I just want performances that include both 'Jane & Alice'.

How would I write a predicate for this query?

Thanks


回答1:


With a list of (distinct) Performer objects, the following predicate should work to find all Performance objects which are related exactly to those performers:

let perf1 = ... // Performer object for "Jane Davies"
let perf2 = ... // Performer object for "Alice Evans"
let list = [perf1, perf2]

let predicate = NSPredicate(format: "performers.@count = %ld AND ALL performers in %@", list.count, list)

but apparently is doesn't. The workaround is to use a SUBQUERY:

let predicate = NSPredicate(format: "performers.@count = %ld AND SUBQUERY(performers, $p, $p in %@).@count = %ld",
      list.count, list, list.count)


来源:https://stackoverflow.com/questions/47000763/many-to-many-relationship-core-data-query-for-specific-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!