2014-12-04 69 views
0

考虑ActionassignedToUser实体的关系。 (Action.assignedTo - >> User)NSPredicate - 具有多对多关系的提取实体

什么是一个查询,它会在assignedTo集合中选择包含user的所有actions

+0

'@ “self.assignedTo ==%@” theWantedUser“'' – Larme 2014-12-04 14:12:52

+0

是assignedTo'一组(一对多的关系,从动作到用户) – user623396 2014-12-04 14:15:23

回答

2

子查询是有点重手。 您可以使用此:

[NSPredicate predicateWithFormat:@"ANY assignedTo.userId == %@", user.userId]; 
+0

同意并接受。 – user623396 2014-12-11 11:21:17

0

您是否使用Xcode发电机为CoreData创建了模型文件?

如果是这样,请检查您User.h文件,你会看到这样的事情:

@property (nonatomic, retain) NSSet   *actions; 

这意味着你可以调用用户只调用所有的动作:

NSSet *userActions = user.actions; 

不需要使用谓词。

如果你仍然想使用一个谓语,谓语应该是这样的:

NSPredicate *userPredicate = [NSPredicate predicateWithFormat:@"assignedTo == %@",user]; 

如果您需要添加aditional的谓词则应在他们的阵列进行NSCompoundPredicate:

NSPredicate *anotherPredicate= ...; 
//andPredicateWithSubpredicates if you want the both 
//orPredicateWithSubpredicates if you want at least one of them 
NSPredicate *compoundPredicate = (NSPredicate*)[NSCompoundPredicate andPredicateWithSubpredicates:@[userPredicate,anotherPrediate]] 
+0

我同意使用反关系会起作用,但是如果我需要通过'status'过滤行为,那么我仍然需要使用'NSPredicate'。 – user623396 2014-12-04 14:50:09

+0

我知道内部核心数据为多对多关系关联保留一个链接表,所以我 – user623396 2014-12-04 14:59:06

+0

你应该使用NSCompoundPrediate,我已经编辑了我的答案,是你需要的吗? – Fantini 2014-12-04 15:23:23

0

我发现SUBQUERY在这里是正确的答案;它完美的作品:

[NSPredicate predicateWithFormat: 
    @"(SUBQUERY(assignedTo, $a, $a.userId == %ld)[email protected] != 0)", user.userId]; 

,并通过过滤status

[NSPredicate predicateWithFormat: 
    @"(SUBQUERY(assignedTo, $a, $a.userId == %ld)[email protected] != 0) && status != 'Completed'", user.userId]; 
相关问题