Ant's
Ant's

Reputation: 13811

How do I group the results in Grails?

I have a Project class like this :

class Project {
    static hasMany = [ tasks : Tasks , users : User ]
    static belongsTo = User
    String name
    String toString() {
        this.name
    }
}

User class like this :

class User {
    static hasMany = [ project: Project ]
    Profile profile
    String username
    String password
    String toString() {
        this.username
    }
}

And Tasks class like this :

class Tasks {
    static belongsTo = [ user : User, project: Project ]
    boolean completed
    String toString(){
       this.title
    }
}

User will be having many Project and Project will be having many Tasks.

Now I need a way to query the DB to find, all the Tasks that are completed and that belongs to a Project. That is for example say that there are two projects, say P1 and P2. In which P1 has 4 completed Tasks and P2 has 1 completed Tasks. My code need to return something like :

[P1:[t1,t2,t3,t4],P2:[t5]]

I know its easy to find all the Tasks that are completed, which will return like this :

[t1,t2,t3,t4,t5]

But I find it difficult to group them according to their Project.

How can I do this?

Thanks in advance.

Upvotes: 0

Views: 123

Answers (1)

Jarred Olson
Jarred Olson

Reputation: 3243

You can use the groupBy on Collection: API or EXAMPLE

For example:

def completedTasks = Task.findAllByCompleted(true)
def compltedTasksByProject = compltedTasks.groupBy {it.project}

Should give you what you want.

Upvotes: 1

Related Questions