2014-05-13 203 views
-1

enter image description here取數據我必須使用下面的查詢獲取數據:核心數據:從實體

SELECT * FROM t1.guides AS t1 JOIN guide_category_int AS t2 ON t1.id = t2.guide_id WHERE t2.category_id = 'category_id' AND t1.start_date >= 'today()' AND t1.end_date <= 'today()' ORDER BY t1.name ASC 

我如何在覈心數據使用?

+1

你有什麼試過?使用[documentation](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html)以供參考,它有很好的例子。哦,如果你不想使用Core Data,你可以直接使用sql,查看'sqlite3.h'獲取細節。 –

+0

你能展示你的核心數據模型嗎? – jamapag

+0

@jamapag我添加了核心數據模型的屏幕截圖 – parvind

回答

2

你取的請求將是這樣的:

NSManagedObjectContext *context = ... 
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Guides" inManagedObjectContext:context]; 
[fetchRequest setEntity:entity]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"guide.category_id == %@ and start_date >= %@ and end_date <= %@", @"category_id", [NSDate date], [NSDate date]]]; 
[fetchRequest setPredicate:predicate]; 
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; 
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]]; 
[sort release]; 
NSError *error; 
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; 
if ([fetchedObjects count] > 0) { 
    //... 
} 
[fetchRequest release]; 

您也可以使SQLDebug看到原始的SQL請求,並與謂語玩和排序描述你想要的。如何啓用描述there

+0

我打算給出相同的內容,除了我更喜歡將單個謂詞與NSCompoundPredicate結合使用,僅僅是因爲我覺得這樣更容易調試和隔離錯誤。 –

+0

@jamapag之前的條件我必須與其他實體Join_Guide_category_int如何可以在上面的查詢中實現。 – parvind