Search code examples
grailsgrails-orm

many to many relationship on the same class


As the title states, I need to tell grails GORM that a domain class has a many to many relationship to itself. In my system, I have a class "course", this "course" class can have none, one or many correlatives.
Taking the example:

mathematical analysis 2

  • To be able to take the mathematical analysis 2 course, you need to have approved mathematical analysis 1 and physics courses.
  • mathematical analysis 1 does not have any correlatives or courses to be approved to be able to anyone to take the course.

I have the following:

class Course {
    String name
    static hasMany = [correlatives: Course]
    static belongsTo = [target_course: Course]
}

But it does not seem to have the impact in the Data base that I expect.

Im expecting to have a course_course table that has the many to many to itself like the following:

course_course
int id_course_course
int id_correlative_course 
int id_target_course

Am I missing something important here?, help please!


Solution

  • You don't need a many to many table to represent that. While each Course may "have many" correlatives, each correlated course only has one parent.

    This is sufficiently represented by a single table like (heavily depending on any mappings you specify):

    course:
        id (int)
        name (varchar)
        target_course_id (int, nullable)