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

0

My intention is to filter a single line within the results of the previous filter, but returning the same type, so that I can perform a third filter. Here's 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's 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? Thanks any help

    
asked by anonymous 21.02.2017 / 20:22

1 answer

1

I think the dynamics should be different. First we need to fetch the Courses object with the specified _codCourse tag. To do this:

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

With this result, we can move on with the Student object search:

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
}

In this way you have the student variable the result of your search: students who have not taken the _codCourse course yet.

  

And with the result of these searches, I want 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 disciplines variable is a list of the Disciplines object and you are trying to insert a Courses in her Anyway, create / search the Disciplines object first before inserting it in the Disciplines property.

    
05.03.2017 / 18:43