Search code examples
grailsmany-to-manygrails-orm

Grails many to many using a third 'join' class


I read that a m:m relationship often means there is a third class that isn't yet required. So I have m:m on User and Project, and I created a third domain class, ProjectMembership

The three domains are as follows (minimized for illustration purposes):

User

class User {

String name 

static hasMany = [projectMemberships : ProjectMembership]
}

Project Membership

class ProjectMembership {

static constraints = {          
}

static belongsTo = [user:User, project:Project]
}

Project:

class Project {

String name

static hasMany = [projectMemberships : ProjectMembership]

     static constraints = { 
     }
}

If I have the ID of the user, how can I get a list of Project objects that they are assigned to?


Solution

  • There are a handful of ways - here are a couple:

    def user = User.get(userId)
    ProjectMembership.findAllByUser(user).collect { it.project }
    

    or to avoid the query for the User:

    ProjectMembership.withCriteria {
        user {
            eq('id', userId)
        }
    }.collect { it.project }
    

    Be wary of queries that'll return large result sets - you'll end up with a huge in-memory list of project objects.