CoreData谓词使用关系

时间:2019-03-26 16:58:52

标签: swift core-data predicate

我有两个实体-QuotesCustomers。一个客户可以有很多报价。关系是quotescustomers

我想获得一个基于客户名称和电子邮件地址的报价对象,并按日期排序,但是我在尝试格式化谓词时遇到了麻烦……

func getMostRecentQuote(name: String, email: String) -> Quotes? {
   var predicateList = [NSPredicate]()
   let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Quotes")
   let predicate1 = NSPredicate(format: "name CONTAINS[c] %@", name)
   let predicate2 = NSPredicate(format: "email CONTAINS[c] %@", email)
   let orCompoundPredicate = NSCompoundPredicate(type: .or, subpredicates: [predicate1, predicate2])
   predicateList.append(orCompoundPredicate)

   fetchRequest.predicate = NSCompoundPredicate(type: .and, subpredicates: predicateList)
   fetchRequest.fetchLimit = 1

1 个答案:

答案 0 :(得分:1)

可能是从QuotesCustomers的一对一关系,如果没有,则建立一个关系并将其命名为customer

然后使用此单个谓词

let predicate = NSPredicate(format: "customer.name CONTAINS[c] %@ OR customer.email CONTAINS[c] %@", name, email)

如果要过滤不区分大小写的完整字符串CONTAINS实际上是错误的运算符,则最好使用LIKE

let predicate = NSPredicate(format: "customer.name LIKE[c] %@ OR customer.email LIKE[c] %@", name, email)

注意:请以单数形式命名实体,从语义上讲,您的方法将返回一个 Quote ,而不是一个 Quotes