我有两个实体" Office"和"员工"
Office实体属性
officeId - string
officename - string
员工实体属性
employeename - string
emailid - string
并建立多对多关系的关系 - 办公室与员工的关系是"员工"
func SaveData(){
let entityOffice = NSEntityDescription.entityForName("Office", inManagedObjectContext: context)
let newoffice = NSManagedObject(entity: entityOffice!, insertIntoManagedObjectContext: context)
newoffice.setValue("BUI001", forKey: "officeId")
newoffice.setValue("Home builders", forKey: "officename")
let entityEmployees = NSEntityDescription.entityForName("Employee", inManagedObjectContext:context)
let newemploy = NSManagedObject(entity: entityEmployees!, insertIntoManagedObjectContext: context)
// Populate Address
newemploy.setValue("Tom william", forKey: "employeename")
newemploy.setValue("tomus@yahoo.com", forKey: "emailid")
// Add Address to Person
newoffice.setValue(NSSet(object: newemploy), forKey: "staff")
do {
try newoffice.managedObjectContext?.save()
} catch {
let saveError = error as NSError
print(saveError)
}
}
保存数据工作正常。我不知道如何在有关系的实体之间获取。
我如何获取"员工"中的所有员工数据?使用" officeid" "办公室"实体。 谢谢你的推荐
答案 0 :(得分:0)
您需要使用NSPredicate
这样的内容:
let officeId = "BUI001"
let predicate = NSPredicate(format: "ANY self.staff.officeId == %@", argumentArray: [officeId])
let fetchRequest = NSFetchRequest(entityName: "Employee")
fetchRequest.predicate = predicate
现在将此fetchRequest与您的managedContext一起使用,以获取与officeId BUI001相关的所有员工
答案 1 :(得分:0)
let fetchRequest = NSFetchRequest(entityName: “Employee”)
let predicate = NSPredicate(format:”officeId=%@”, "BUI001")
fetchRequest.predicate = predicate
if let fetchResults = try? self.managedObjectContext.executeFetchRequest(fetchRequest)
{
if fetchResults.count > 0 {
for bEntity in fetchResults {
let employeeEntity = bEntity as! EmployeeEntity
// append the details to the employeeDetails
} else
{
print(“Details Not Added")
}
}
return employeeDetails