matuda
matuda

Reputation: 195

How to maintain order in grails many-many relationship

My project requires me to maintain the insertion and retrieval order in a many-many relationship. By default, groovy saves the elements as a Set in many-many relationship. I want to do it in a List. I am not sure how to update the relationship to use List instead of Set. Any help would be appreciated.

class Course{
        static belongsTo = Teacher
        static hasMany = [teacher:Teacher]

        static mapping = {
            teacher joinTable : [name: TeacherCourse]
        }
    }

    class Teacher{

        static hasMany = [course:Course]
        static mapping = {
            course joinTable : [name: TeacherCourse]
        }
    }

save() call on either Teacher or Course also inserts a new row in TeacherCourse table. It works with no issues. In Database there the tables are:- Teacher (PK: Id) Course (PK: Id) TeacherCourse(PK: [Teacher_id,Course_id])

Is there a way I can maintain the order of insertion and retrieval in many-many relationship?

Thank you..

Edit In controller save()

def courseInstance = new Course()
List <Teacher> teacherList= []
teacherList.add(Teacher.findById(65))
teacherList.add(Teacher.findById(36))
courseInstance.courseUnits = teacherList
courseInstance.save(flush:true)

Upvotes: 1

Views: 380

Answers (1)

rcgeorge23
rcgeorge23

Reputation: 3694

Try this:

class Course {
    List teachers

    static belongsTo = Teacher
    static hasMany = [teachers:Teacher]

    static mapping = {
        teachers joinTable : [name: TeacherCourse]
    }
}

class Teacher {
    List courses

    static hasMany = [courses:Course]
    static mapping = {
        courses joinTable : [name: TeacherCourse]
    }
}

Reference

Upvotes: 1

Related Questions