2012-04-01 56 views
1

更新以下問題: 我們能夠使用父實體獲取請求通過使用fatherChild關係來查詢子實體。示例查詢如下:如何爲多個實體創建一個fetchRequest?

NSPredicate *myPredicate = [NSPredicate predicateWithFormat:@"fatherChild.name LIKE 'fx'"]; 

現在,我們正在努力做的是使用上面的謂詞,但另一個地方,我們要找到孩子的父親定名稱的另一個條件。我們用下面的代碼

NSPredicate *myPredicate = [NSPredicate predicateWithFormat:@"name LIKE 'john' AND ANY fatherChild.name in 'fx'"]; 

但程序崩潰與例外: [__NSCFString countByEnumeratingWithState:對象:伯爵:]:無法識別的選擇發送到實例0xad49c40

通過我們看到,我們可以使用子查詢的例子閱讀但不知道我們的情況是什麼語法,我們有一個具有一對多關係的實體。任何幫助,將不勝感激?

謝謝。

問題: 我們有一個包含三個實體的數據模型:父親,母親和孩子。請參閱圖片以供參考。

我們有一個例子查詢請求對父親實體如下:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Father" 
              inManagedObjectContext:managedObjectContext]; 
    [request setEntity:entity]; 

    NSString *attributeName = @"name"; 
    NSPredicate *myPredicate = [NSPredicate predicateWithFormat:@"%K like %@", 
    attributeName, searchField.text]; 

我們對母親和兒童的實體類似的查詢請求。我們想要做的是創建一個查詢來結合父親和母親的實體。例如,我們希望在單個查詢中搜索父名= Mike和Mothers name = Jen。我們該怎麼做呢?

感謝您的回覆。

+1

你是說你想從一個單一的查詢中得到兩種不同類型的結果,或者你正在嘗試尋找哪裏有'mother.name == foo'和'father.name == bar'的孩子? – 2012-04-01 21:28:03

+0

後者是我們正在努力做的。謝謝! – user1306828 2012-04-01 21:58:06

回答

1

我們發現我們可以使用SUBQUERY來解決問題。

NSPredicate *myPredicate = [NSPredicate predicateWithFormat:@"name LIKE %@ AND fatherMother.name LIKE %@ AND (0!=SUBQUERY(fatherChild,$varChild,$varChild.name=%@)[email protected])",dad.text, mom.text, baby.text];         

這裏fatherMotherfatherChild有關係的名字。

dad.text,mom.text和baby.text是UITextField值。

+0

@tangqiaoboy我在這裏有類似的問題(http://stackoverflow.com/questions/11934763/nspredicate-on-nested-object-nsset-to-filter-the-result-during-nsfetchrequest)...我有嘗試了下面的謂詞:[NSPredicate predicateWithFormat:@「mode = 0 AND ALL(SUBQUERY(enrollments,$ varEnrollment,$ varEnrollment.mode = 0))」]但它不適合我,在我的謂詞註冊中是我的關係...你能建議我在哪裏做錯了嗎? – yunas 2012-08-15 09:53:53

+0

@yunas對不起,我不知道,你應該問'user1306828',他是答案的作者。我只是幫他在答案中格式化代碼。 – tangqiaoboy 2012-08-29 04:15:37