问题
This is the structure of my core DB tables. Wanted to create a subquery in a predicate, Below is the description of the query.
Generate all unique Submission, where SubmisisonField.value matches with an array. This query for image on top.
For Second image which is having Employee table request is: Generate all ActivityFeedCard, where Employee name matches to string. Now id field in Employee is the same field which is SubmissionField.value or we can say SubmissionField.value == Employee.id. We have to search by EMployee first name, last name etc, Thank you so much.
let fetchCardsContext = CoreDataManager.shared.getNewBackgroundContext(name: "Fetch Cards for display BG Context")
var predicate: NSPredicate?
self.displayedCards.removeAll()
predicate = NSPredicate(format: "SUBQUERY(submission.submissionTemplate.submissionField.value, $v, $v IN %@).@count > 0", empArray)
self.displayedCards = ActivityFeedCard.fetchAndSort(in: fetchCardsContext, predicate: predicate, sortOptions: nil) ?? [ActivityFeedCard]()
回答1:
You want to "generate all unique Submission". So the fetch request should be based on the Submission
entity. Relative to the Submission
entity, submissionTemplate.submissionField.value
is a collection (because the submissionField
relationship is to-many). You want to include in your fetch only those Submission
objects where the collection "matches an array". Assuming that you mean "if the collection and the array have any values in common", then the predicate to use is:
NSPredicate(format:"SUBQUERY(submissionTemplate.submissionField.value, $v, $v IN %@).@count > 0",yourArray)
Or in words: "the count
of (values, $v
, from the submissionTemplate.submissionField.value
collection that are IN
the array) is greater than zero".
来源:https://stackoverflow.com/questions/59777306/core-data-subquery-with-multiple-relationship