Query based on relationship, using Nspredicate in Core Data

Asked

Viewed 305 times

1

I have a one-to-many relationship between entities Pai and Filho, where a Pai may have any or N Filho. Using the Core Data, how do I fetch all the Filho, basing my search for a Pai.

For example: I have a Pai who owns the Id 1. I need to fetch all the Filho who has the Pai with the Id 1.

1 answer

2

Simply use the names of the properties, both of the entity and of the relationship in the condition of the NSPredicate to make the request.

Swift:

let request = NSFetchRequest(entityName: "Filho")
request.predicate = NSPredicate(format: "RelacionamentoPai.Id == %d", 1)

Objective-C:

NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Filho"];
[request setPredicate:[NSPredicate predicateWithFormat:@"RelacionamentoPai.Id == %d", 1]];
  • Blz, what if it’s a long-term relationship? This does not exist but suppose it exists, it would be through the intermediate table that Core Data itself creates?

  • In relation to to-manyif you use the keyword any. Example: [NSPredicate predicateWithFormat:@"ANY RelacionamentoPai.Id == %d", 1];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.