Swift 3/Realm - How to filter an Object inside another filter

Asked

Viewed 129 times

0

My intention is to filter a single line within the previous filter results, but returning the same type, so I can perform a third filter.
This is my attempt:

    func salvarDadosAluno(_codPessoa: String, _codCurso: String){

    let realm = try! Realm()

    let aluno = realm.objects(Alunos.self).filter("codPessoa == %@", _codPessoa).first

    //Cannot convert value of type 'Alunos' to expected 'Object.type'
    let curso = realm.objects(aluno).filter("codCurso == %@", _codCurso).first

    print(cursos)

    }

Here is my DB:

class Alunos : Object{

   dynamic var codPessoa: String = ""
   dynamic var raPessoa: String = ""
   dynamic var nomePessoa: String = ""
   let cursos = List<Cursos>()
}

class Cursos : Object{

   dynamic var codCurso: String = ""
   dynamic var desCurso: String = ""
   let disciplinas = List<Disciplinas>()

}

And with the result of these searches, I want to insert more disciplines for this student, in this filtered course, like this:

try! realm.write {

            curso?.disciplinas.append(curso)

}

How to proceed?
I appreciate any help

1 answer

1


I believe the dynamic must be different. First we need to find the object Courses with the code _codCurst specified. For this purpose:

let predicateCursos = NSPredicate(format: "codCurso == %@", _codCursos)
let curso = realm.objects(Cursos.self).filter(predicateCursos).first // retorna Cursos?

With this result, we can move forward with the search for the object Students:

if  let curso = realm.objects(Cursos.self).filter(predicateCursos).first {
    let predicateAlunos = NSPredicate(format: "codPessoa == %@ AND NOT %@ IN cursos", _codPessoa, curso)
    let aluno = realm.objects(Alunos.self).filter(predicateAlunos).first
    // Retorna Alunos?. Acima o aluno com o código _codPessoa que não possui o curso com o código _codCursos
}

That way you have in the variable pupil the result of your search: students who do not yet take the course _codCurst.

And with the result of these searches, I wish to insert more disciplines for this student, in this filtered course

try! realm.write {
     curso?.disciplinas.append(curso)
}

In the above case there is an inconsistency in your code: the variable disciplines is a list of the object Disciplines and you’re trying to insert a Courses in it. Anyway, Create/search the object Disciplines first before inserting it into the property disciplines.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.