Search code examples
grailsgrails-ormgrails-domain-class

Grails set mapping table of 3 classes


I am new to grails. I have 3 classes as follws

class Cycle 
{
    int year
    int quarter
}

class User
{
    String username, password           
}           

class Role
{
    String roleName 
} 

The User and Role tables are independent and they stores details of all employees and Available roles respectively. An employee can have many roles in each cycle. so i want a mapping table like

enter image description here

to find what all roles belongs to an employee in a particular cycle. How do i set proper relation between these classes to solve this scenario so that if i have a cyle and a user , i can find out what all roles the user has in that cycle also if i have a user i can find which all cycles he involved an his roles in each of these cycles


Solution

  • Following the comment. You should create a table between User and Cycle

    class UserCycle
    {
        User user
        Cycle cycle
        static hasMany = [roles: Role]
    }
    

    Role class should look like this:

    class Role
    {
         String roleName
         UserCycle userCycle
    }
    

    and in code You can refer to that like:

    UserCycle uc = ...
    def roles = uc.roles.list(params) //list of roles
    def cycle = uc.cycle
    def user = uc.user
    

    to add

    uc.addToRoles(/*Your role*/)
    

    to remove

    uc.removeFromRoles(/*Your role*/)