简体   繁体   中英

How to fetch data from core data using Entity relationship in swift?

I have two entities "Office" and "Employee"

Office Entity attributes are

         officeId - string
          officename - string

Employee Entity attributes are

         employeename - string
         emailid - string

And have relationships as many to many relationship - Office to Employee relationship is "staff"

                 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)
    }




}

The saving data is working fine.I have no idea how to fetch between entities which have relationship.

How can i fetch all the employees data in "Employee" enitity by using "officeid" of "Office" entity. Thanks in advace

You need to use an NSPredicate like this :

let officeId = "BUI001"
let predicate  = NSPredicate(format: "ANY self.staff.officeId == %@", argumentArray: [officeId])
let fetchRequest = NSFetchRequest(entityName: "Employee")
fetchRequest.predicate = predicate

Now use this fetchRequest with your managedContext to fetch all the employee related to the officeId BUI001

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM