ELKA
ELKA

Reputation: 735

NSPredicate count > 0 on many to many to many relationship

I have a three level hierarchy of objects in CoreData: Let say Entity A has a set of Entities B and Entity B has a set of Entities C. (A many-to-many B and B many-to-many C)

I want to get all the entities A such that the As have Bs and Cs. I am trying to use a predicate when fetching Entities A: NSPredicate(format: "ANY bs.cs.@count > 0")' but i am getting this error: Unsupported function expression count: (bs.cs)

Any idea on how to correctly write this query?

Upvotes: 1

Views: 798

Answers (1)

Martin R
Martin R

Reputation: 539835

The "ANY" operator does not work with nested to-many relationships, therefore you need a "SUBQUERY" (which unfortunately is not very well documented). Something like this should work:

NSPredicate(format:"SUBQUERY(bs, $b, $b.cs.@count != 0).@count != 0")

The SUBQUERY(..) part returns all related B objects which have at least one related C object. The final .@count != 0 part checks that there is at least one related B object with this property.

Upvotes: 3

Related Questions