2014-05-13 201 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