Core Data subquery with Multiple Relationship

白昼怎懂夜的黑 提交于 2020-02-16 04:01:58

问题


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

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