2014-12-04 51 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]; 
相關問題