Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data predicate to filter by a subentity attribute

I have been looking for this but I found nothing and I think it's unsupported by Core Data. Anyway, let's see it:

I have 3 entities: Ticket, TicketLine and CheffLine.

A Ticket contains multiple TicketLines (Ticket.lines). **CheffLine** inherits from TicketLine.

Now I want to fetch the tickets (by means of a NSFetchedResultsController), but filtering the tickets that have at least one CheffLine with a cheffStatus greater than 0. The problem is that cheffStatus is an attribute of the CheffLine entity, so I make this predicate:

[NSPredicate predicateWithFormat:@"0 != SUBQUERY(lines, $x, $x.cheffStatus > 0).@count)"];

But when executed, I get this error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to generate SQL for predicate (0 != SUBQUERY(lines, $x, $x.cheffStatus > 0).@count) (problem on RHS)'

I noticed that if the query is done using $x.someVariableInTheTicketLineEntity instead of $x.cheffStatus, it works. I also tried to use CAST, but obtained the same result

[NSPredicate predicateWithFormat:@"0 != SUBQUERY(lines, $x, CAST($x, 'CheffLine').cheffStatus > 0).@count)"];

Is there any way of doing this query? Remember that it must work inside a NSFetchedResultsController.

like image 529
quarac Avatar asked Sep 30 '22 00:09

quarac


1 Answers

Ok, I found that there's no solution. Look at this:

How can you reference child entity name in a predicate for a fetch request of the parent entity?

The way to go is to fetch the results in 2 separate requests and then merge manually, so forget about the NSFetchedResultsController.

like image 58
quarac Avatar answered Oct 19 '22 19:10

quarac