John
John

Reputation: 441

Realm Database Design

I have an example database as follows:

class Company:Object {
    dynamic var companyName = ""
    let employees = List<Employee>()
}

class Employee:Object {
    dynamic var companyName = "" // Is this required?
    dynamic var name = ""
    dynamic var age = ""
}

Is the companyName property in class Employee neccessary? If not how would I reference the employees that belongs to a particular company in the query.

Upvotes: 1

Views: 452

Answers (1)

bcamur
bcamur

Reputation: 894

You can use linkingObjects feature of Realm for that purpose like this:

class Company:Object {
    dynamic var companyName = ""
    let employees = List<Employee>()
}

class Employee:Object {
    dynamic var name = ""
    dynamic var age = ""
    var company: Company? {
        return linkingObjects(Company.self, forProperty: "employees").first
    }
}

This approach saves you the effort to keep your Employee object's companyName property accurate and it also saves you space since company here is not stored. If you choose this path you can get your Employee's company object easily like this: (this returns nil if Employee is not associated to any Company)

let aCompany = someEmployee.company

And to answer your question

If not how would I reference the employees that belongs to a particular company in the query.

you already have a way to do this since you store a Company's Employee's in its list employees, so you can just use that property like this to get Employees that belong to a company:

let aCompanysEmployees = someCompany.employees

Upvotes: 1

Related Questions