Search code examples
ioscore-datamany-to-manynspredicatensfetchrequest

Core-data: querying distinct entities in many to many relationship with middle entity and condition


My core data model is as following:

enter image description here

where code is NSInteger in both entities and so is value. This maps the following data (sample data, real case scenario is hundreds of rows x hundreds of columns), where columns are WorkCategories, WCn, rows are Features, Fn and single cells are Feasibilities:

enter image description here

Given a set of Features, I need to retrieve all the distinct WorkCategories whose columns has all Feasibility value(s) greater than one. WorkCategories should also be ordered by their ascending code. So:

  • If my feature set is (F1,F3), the result should be (WC3, WC4);
  • If my feature set is (F2,F3), result should be (WC1,WC4);
  • If my feature set is (F1,F2,F3), result should be (WC4).

I achieved it by querying all the WorkCategories in Core data and then by filtering them via code using their feasibility property.

My question: is there a way to do this in core data using only a single FetchRequest (i.e., executeFetchRequest:error: output should already be the distinct WorkCategories whose columns in the Feasibility table has all value(s) greater than one)?


Solution

  • This predicate for WorkCategories should do it:

    predicateWithFormat:@"SUBQUERY(feasibility, $feasibility, $feasibility.value > 1 AND $feasibility.feature IN %@).@count = %lu", featuresSet, (unsigned long)[featuresSet count]

    The subquery gets feasibilities with value > 1 and a feature in the set. If the number of found feasibilities is equal to the number in the set then all feasibilities in the set have a value > 1.