pankaj
pankaj

Reputation: 8348

Join in Core Data entities without any defined relationship

I have two entities Product and Variant in my core data database but haven't defined any relationship. I am adding data in the tables from some web services. The tables have prodct_id as common column and I want to use it as relationship.

I want to fetch data as per following query:

select * from Product, Variant where Product.product_id = Variant.product_id

How can I get the desired data as I am new to core data?

Upvotes: 0

Views: 166

Answers (1)

MeloS
MeloS

Reputation: 7938

CoreData is not all the same like a relational database, so there is no easy way to do this.

My solution is use NSPredicate to first retrieve all unique product_id, then fetch all Product and Variant with these product_id, and at last, pair them together with code.

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

Upvotes: 0

Related Questions