我試圖用一個謂詞構建一個提取請求,該請求使用子查詢在覈心數據中進行一些關係。我的模式是這樣的:核心數據SUBQUERY語法問題
所有我掌握的信息是ChargeCodeType和員工。我想要做的是獲得屬於Employee的所有TimeEntries,並且總結TimeEntry中的小時數列。我有一個工作子查詢的格式如下:
static func fetchRequestForChargeCodeTypeWithEmployeeNumber(context : NSManagedObjectContext, chargeCodeType : String, employeeId : Int) -> NSFetchRequest{
let entity = NSEntityDescription.entityForName("ChargeCodeType", inManagedObjectContext: context)
let fetchRequest = NSFetchRequest()
fetchRequest.entity = entity
let typePredicate = NSPredicate(format: "type == %@ AND SUBQUERY(chargeCodes, $t, ANY $t.timeEntries.person.employeeID == %@)[email protected] != 0", chargeCodeType, NSNumber(integer:employeeId))
fetchRequest.predicate = typePredicate
return fetchRequest
}
不過,我相信這裏的問題是「ANY」關鍵字和正在發生的事情是,如果我有多個員工時,我總結了收費代碼時間條目,當我總結收費代碼上的時間條目時,我會爲多個用戶獲取時間條目。這裏有更多相關的代碼展示了我如何使用謂詞。
func constructDataSourceYearToDateUtilization(chargeCodeType : String){
let chargeCodeTypeFetchRequest = CoreDataUtilities.fetchRequestForChargeCodeTypeWithEmployeeNumber(coreDataStack.managedObjectContext, chargeCodeType: chargeCodeType, employeeId: employee.employeeID!.integerValue)
chargeCodeTableDataSource = [YTDChargeCodeModel]()
do {
if let chargecodeType = try coreDataStack.managedObjectContext.executeFetchRequest(chargeCodeTypeFetchRequest).first as? ChargeCodeType {
let chargeCodes = chargecodeType.chargeCodes?.allObjects as? [ChargeCode]
yearToDateHoursSum = 0
for chargeCode in chargeCodes! {
let ytdChargeCodeModel = YTDChargeCodeModel()
ytdChargeCodeModel.chargeCode = chargeCode
ytdChargeCodeModel.fullChargeCode = chargeCode.chargeCode
ytdChargeCodeModel.chargeCodeDescription = chargeCode.chargeCodeDescription
ytdChargeCodeModel.totalHours = chargeCode.valueForKeyPath("[email protected]") as! Int
yearToDateHoursSum = yearToDateHoursSum + ytdChargeCodeModel.totalHours
chargeCodeTableDataSource.append(ytdChargeCodeModel)
}
totalHoursLabel.text = "\(yearToDateHoursSum)hrs"
//Sort by charge code name.
chargeCodeTableDataSource.sortInPlace { $0.fullChargeCode!.compare($1.fullChargeCode!) == .OrderedAscending }
} else {
print("Could not get the charge code type")
totalHoursLabel.text = "0hrs"
}
} catch let error as NSError {
print("Hit error when fetching user profile with error message: \(error.localizedDescription)")
}
tableView.reloadData()
}
是否有任何方法使這個工作與子查詢或我應該重新寫方法?