1
votes

in core data, I have two entities. XMPPUserCoreDataStorageObject & XMPPGroupCoreDataStorageObject.

XMPPUserCoreDataStorageObject has a property which holds an array of XMPPGroupCoreDataStorageObject (@property (nonatomic, strong) NSSet * groups;)

XMPPGroupCoreDataStorageObject also has a property which hold an array of XMPPUserCoreDataStorageObject (@property (nonatomic, strong) NSSet* users;)

I want to query the XMPPUserCoreDataStorageObject which is group by XMPPGroupCoreDataStorageObject. This is many-to-many mapping.

How can I achieve this?

2

2 Answers

2
votes

You cannot group by a many-to-many relationship because the child entity (User in your case) would occur more than once.

Instead, fetch by what you want to group by (Group in your case). For displaying these in e.g. a table view, use the fetched groups to populate the table view section headers, and display the associated Users in the table view rows.

2
votes

Another solution, if you are able to modify the data model, is to implement an intermediate entity to model the many-many relationship. So rather than:

User <<<--->>> Group

you would have

User <--->>> GroupMember <<<---> Group

You can then base your fetch on the GroupMember entity. Since this has to-one relationships to both User and Group, you could use a NSFetchedResultsController to do the grouping, with sectionNameKeyPath set to "group.groupName" (or whatever attribute), and then populate the table view based on attributes of the user relationship (e.g. user.userName). But the downside is that creating and deleting the relationship involves a bit more work inserting/deleting the GroupMember objects.