Fetch relational entity from core data using magical record

231 views Asked by At

I'm maintaining a project already using magical record (https://github.com/magicalpanda/MagicalRecord/wiki) as Core Data bridging, and I want to write a fetch function, but don't know how to. Following is the requirement:

I have entity Person and Event. A Person can have no or many Events, for example sightseeing, playing football... In *.xcdatamodelId file, Person entity is linked with Event entity (to-many relationship). In attributes table of Person entity, I see NO attribute relating to Event entity (Yes, NO eventId in Person entity). In Event "table", there is also NO personId. The only thing that connect Person and Event is the "to-many" relationship that has been set.

Event entity has a "type" attribute: Entity.type may be equal to "sport","leisure", etc. Event entity also has a "date" value.

This is what I want to fetch: I want to fetch all Person that has at least one Event of type "sport", and I want to also get Entity.date which is the oldest.

If it was SQLite, I would join Person and Entity table, where Entity.type == "sport". If there was any records of the join, then I will sort the table based on Event.date and then will retrieve the first one.

But how can I do that with Magical Record?

EDITTED: I know how to set predicate to search for Person, such as:

NSPredicate *peopleFilter = [NSPredicate predicateWithFormat:@"Department IN %@", @[dept1, dept2]];
NSArray *people = [Person MR_findAllWithPredicate:peopleFilter];

But in my situation Person has no eventId, Event has no personId, so this will not apply.

1

There are 1 answers

0
thomasdao On BEST ANSWER

Finally I got the solution. This can be done as simple as following:

 NSPredicate *peopleFilter = [NSPredicate predicateWithFormat:@"ANY events.eventType contains %@",@"love"];
    NSArray *people = [Person MR_findAllWithPredicate:peopleFilter];
    return people;

(A person has an array of events)