复杂核心数据谓词与一对多关系 [英] Complex Core Data predicate with to-many relation

查看:161
本文介绍了复杂核心数据谓词与一对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个实体。文件夹,Feed& FeedItem

I have 3 entities. Folder, Feed & FeedItem

我需要抓取含有未读FeedItem的Feed和Feed的文件夹

I need to fetch Folders which have feeds and feeds which have unread FeedItems

NSPredicate * predicate = [NSPredicate predicateWithFormat:@" feeds.@count > 0 AND feeds.feedItems.unread == 0 "];

我收到此错误

'NSInvalidArgumentException ',reason:'to-many key not allowed here'

'NSInvalidArgumentException', reason: 'to-many key not allowed here'

如何构造这样的谓词?是否有可能?

How do I construct such a predicate? Is it possible at all?

推荐答案

它不喜欢 feeds.feedItems.unread == 0 ,因为 feeds feedItems 返回一个集合,因此谓词不知道哪个对象测试。

It doesn't like feeds.feedItems.unread==0 because feeds and feedItems return a set so the predicate doesn't know which object to test.

尝试任何feeds.feedItems.unread == 0

但是,你要向后走。这将更容易获取 FeedItem 其中 unread == 0 ,然后请求每个获取项目的 feed.folder 以获取文件夹。

However, you're going about this backwards. It would be easier to fetch all FeedItem where unread==0 and then ask for each fetched item's feed.folder to get the folder.

复杂谓词通常是一个糟糕的主意,因为您无法预测随着对象图形在复杂性增长以及数据本身大小增长而执行的搜索的资源消耗。你应该走的关系,而不是可以的。

Complex predicates are usually a bad idea because you can never predict the resource consumption of the search they perform as the object graph grows in complexity and the data itself grows in size. You should walk relationships instead when you can.

你需要一个SUBQUERY。尝试:

Looking at this again it looks like you need a SUBQUERY. Try:

NSPredicate *p = [NSPredicate predicateWithFormat:@"(0 != SUBQUERY(feeds, $x, (0 != SUBQUERY($x.feedItems, $y, $y.unread==0).@count)).@count)"];

子查询记录不良,但它们本质上是嵌套谓词。它们的格式为:

Subqueries are poorly documented but they are essentially nested predicates. They have the format:

SUBQUERY(objects, singleObjectVariable, expression-for-single-object)

我相信子查询返回集合,所以你可以使用任何set操作符,你可以嵌套它们。当你嵌套他们,他们走的关系图,所以你可以让他们任意深。

I believe that subqueries return sets so you can use any of the set operators on them and you can nest them. When you nest them, they walk the relationship graph so you can make them arbitrarily deep.

这篇关于复杂核心数据谓词与一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆