0

I've got a complex NSPredicate problem that I just cannot solve.

My data structure is as follows:

Category - has many Titles

Title - has many Products

Title - has latestProduct property (title.latestProduct)

Titles can be excluded via excluded property (title.excluded = YES) Products can be excluded via excluded property (product.excluded = YES)

The result I am looking for: I need to fetch a list of all categories in the system, however I want to exclude categories where:

  • All category titles are excluded (category.titles.excluded == YES)

OR

  • All latest products are excluded (category.titles.latestProduct.excluded == YES)

OR (and this is the tough part for me)

  • The SUM of the count of (category.titles.excluded == YES) and count of (category.titles.latestProduct.excluded == YES) is equal to the count of category titles (category.titles.count)

I can describe my problem in plain english but cannot work out the proper way to format this as a predicate. Any help would be greatly appreciated thanks!

Larme
  • 24,190
  • 6
  • 51
  • 81
Nick Kirsten
  • 1,187
  • 11
  • 27
  • I'd go with subquery (check that: http://stackoverflow.com/questions/9803971/subquery-in-nspredicate-and-nsinvalidargumentexception) – Larme Jun 27 '14 at 15:14
  • I suggest you to make a predicate with blocks, because inside the block you can create such complex query, literally easily and quickly. – holex Jun 27 '14 at 15:30
  • unfortunately blocks wont work with core data fetch queries. As for subqueries - I have been using them but unfortunately I am unser how to add the 2 counts together for the last part of the query – Nick Kirsten Jun 28 '14 at 10:50
  • @Mamela, who said it is not working? I'm not using anything else, but block-based predicates for CoreData; however, I've always built the databases up in spirit of CoreData, so I have had no problem ever. according to your post you could have done the same thing in the case of your database. If I had known more about your entities I would have created the block-based request for you as answer. – holex Jun 30 '14 at 08:33

1 Answers1

0

So I finally worked out the way to do this using a combination of the ANY clause as well as a subquery. The predicate is as follows:

ANY productTitles.excluded == nil && SUBQUERY(productTitles, $x, SUBQUERY($x.products, $y, $y.excluded == nil).@count != 0 ).@count != 0

I think the subquery is basically how the "ANY" clause works anyway but I could not figure out how to do an ANY clause for a subquery of a subquery.

Nick Kirsten
  • 1,187
  • 11
  • 27