Accessing one table values from other table in Realm


(Ahsan) #1

I have two tables named Class and Student and all I want is to access Class values to be accessed by my Student object. And for that what I’ve got to know from Realm swift documents is the use of Linking Objects. Need help in implementing this idea. Here is my code, Any help would be appreciated.

class ClassModel: Object {
    @objc dynamic var classId = 0
    @objc dynamic var className = ""
    @objc dynamic var classNotification = 0
    var students = List<StudentModel>()

    override class func primaryKey() -> String {
        return "classId"
    }
}
class StudentModel: Object {

    @objc dynamic var sId = 0
    @objc dynamic var rollNum = ""
    @objc dynamic var firstName = ""
    @objc dynamic var lastName = ""
    @objc dynamic var DOB = ""
    @objc dynamic var gender = ""
    @objc dynamic var picture = ""
    @objc dynamic var pictureThumbnail = ""
    @objc dynamic var pickupStatus = 0
    let fromClass = LinkingObjects(fromType: ClassModel.self, property: "students")

    override class func primaryKey() -> String {
        return "sId"
    }
}

//I want something like this from student table.

func fetchStudents(byCLassId: Int) -> Results<StudentModel> {
        let realm = try! Realm()
        let predicate = NSPredicate(format: "classId == %i", byCLassId)
        return realm.objects(StudentModel.self).filter(predicate)
    }
// and result should be like a single object which have similar classId. 

(Zsolt Jandzso) #2

Your models seems okay. What do you want to exactly achieve?


(Ahsan) #3

Hi, thanks for reply, I want to access classId of ClassModel from StudentModel. like JOIN works in SQL, i don’t get it how to do it in realm.


(Zsolt Jandzso) #4

Thats how you need to do it.

The one tricky part is the data save: when you are creating a new class, you should add the students to the students list and save that ( there is no need to save the Student model). In this way, you will have the connection between the two models.


(Ahsan) #5

you mean to sat that I do not create student table, then how do i save that data for students ?


(Zsolt Jandzso) #6

You don’t need to make a realm.add(student) call if you added a Class with students.
There is already a reference on the Class.students, you should not save again - thats duplication.