0

我有一个像下面这样的核心数据模型的结构:NSPredicate和核心数据:检索关系中的对象

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 

在一个UIViewController我使用的是下面的断言相关的NSFetchRequest

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

谓词运作良好。我能够检索与特定客户关联的一个(或多个)订单的产品。

现在我不得不再增加一个步骤。查找特定客户的最后订单(按日期排序)。我尝试了以下谓词,但它不工作:

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

其中orderDateNSDate类型。

我必须使用SUBQUERY吗?我怎样才能做到这一点?先谢谢你。

回答

1

我能够通过固定的日期外的问题。换句话说,我首先计算了特定客户端的最后订单日期,然后将其传递给感兴趣的元素(实现请求的元素)。

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

我不知道如果可能是正确的,但它的工作原理。

希望它有帮助。

+0

当您只需要一条记录时,您确实可以使用谓词。 – ggfela 2012-02-22 10:58:37

2

你可以在你的fetchrequest上使用sortDescriptor(fetchrequest需要一个sortdescriptors数组)。

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

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

编辑:见NeverBe评论

+0

我不知道这可能是一个解决方案,因为我从产品实体创建请求。 – 2012-02-17 17:23:01

+0

当您使用基于SQLite的CoreData时,您可以直接访问数据库。在代码中排序会很慢,因为您需要很多CoreData调用。 – ggfela 2012-02-17 17:41:17

+3

这是一个解决方案。您应该设置一个正确的键来对描述符进行排序(productOrders.order.orderDate)并将提取限制设置为1以提取请求。还有排序需要desc – NeverBe 2012-02-17 17:43:45