我的核心数据库中有两个实体Product和Variant,但没有定义任何关系。我在一些Web服务的表中添加数据。这些表有prodct_id作为公共列,我想将它用作关系。
我想按照以下查询获取数据:
select * from Product, Variant where Product.product_id = Variant.product_id
如果我不熟悉核心数据,我怎样才能获得所需数据?
答案 0 :(得分:0)
CoreData与关系数据库不完全相同,因此没有简单的方法可以做到这一点。
我的解决方案是使用NSPredicate
首先检索所有唯一的product_id
,然后使用这些Product
获取所有Variant
和product_id
,最后一对他们和代码一起。
NSEntityDescription *productEntity;
NSEntityDescription *variantEntity;
fetchRequest.resultType = NSManagedObjectResultDictionary;
fetchRequest.propertiesToFetch = [NSArray arrayWithObject:[[variantEntity propertiesByName] objectForKey:@"product_id"]];
fetchRequest.returnsDistinctResults = YES;
NSArray *productIDDictionaryArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
NSArray *productIDArray = [productIDDictionaryArray valueForKey:@"product_id"]; //this is magic
NSFetchRequest *productFetch = [[NSFetchRequest alloc] init];
[productFetch setEntity:productEntity]
[productFetch setPredicate: [NSPredicate predicateWithFormat: @"(product_id IN %@)", productIDArray]];
NSError *error;
NSArray *products = [MOC
executeFetchRequest:productFetch error:&error];
NSFetchRequest *variantFetch = [[NSFetchRequest alloc] init];
[variantFetch setEntity:variantEntity]
[variantFetch setPredicate: [NSPredicate predicateWithFormat: @"(product_id IN %@)", productIDArray]];
NSError *error;
NSArray *variants = [MOC
executeFetchRequest:variantFetch error:&error];
//pair product and variants with the same product_id using code