Lorenzo B
Lorenzo B

Reputation: 33428

NSPredicate and Core Data: retrieve objects among relationships

I have a Core Data model structure like the following:

Product <-->> OrderProduct where the relationship (from Product to OrderProduct) is called productOrders while the inverse is called product

Order <-->> OrderProduct where the relationship is called orderProducts while the inverse is called order

Client <-->> Order where the relationship is called orders while the inverse is called client

Within an UIViewController I'm using a NSFetchRequest associated with the following predicate:

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"(ANY productOrders.order.client.code == %@)", clientCode];

The predicate works well. I'm able to retrieve products for one (or more) orders that are associated with a specific client.

Now I have to add another step. Find the last order (ordering by date) for a specific client. I've tried the following predicate but it doesn't work:

  NSPredicate* predicate = [NSPredicate predicateWithFormat:@"(ANY productOrders.order.client.code == %@ AND [email protected])", clientCode];

where orderDate is of type NSDate.

Do I have to use a SUBQUERY? How can I achieve this? Thank you in advance.

Upvotes: 0

Views: 2610

Answers (2)

Lorenzo B
Lorenzo B

Reputation: 33428

I was able to fix the issue passing the date externally. In other words, I first calculated the last order date for a specific client and then I passed it to the interested element (the one that implement the request).

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"ANY productOrders.order.client.code == %@ AND productOrders.order.orderDate == %@", clientCode, lastDate];

I don't know if could be correct but it works.

Hope it helps.

Upvotes: 1

ggfela
ggfela

Reputation: 1152

You can use a sortDescriptor on your fetchrequest (fetchrequest takes an array of sortdescriptors).

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"productOrders.order.orderDate" ascending:NO];

[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];

edit: see NeverBe comment

Upvotes: 2

Related Questions