Steve
Steve

Reputation: 325

Grails query rows to arrays

I'm new to Groovy and Grails. I think this problem probably has an easy answer, I just don't know it.

I have a database table:

id | category | caption | image | link

I have a query that lets me retrieve one row for each distinct item in 'category.'

I'm trying to return a map where each row is an array named by it's category.

e.g., If I select the rows:

[{category='foo', caption='stuff', ...} {category='bar', caption='things', ...}]

I want to be able to:

return [foo:foo, bar:bar]

where:

foo = [caption='stuff', ...]
bar = [caption='things', ...]

Thanks for any help.

Upvotes: 0

Views: 890

Answers (2)

Alidad
Alidad

Reputation: 5538

You can transform your list using collect in Groovy, however, the result depends on the source data. I could not infer from your post that if you are returning one item per category or multiple.

def ls = Category.list()
def newList = ls.collect {
    [(it.category):['caption':it.caption,'image':it.image,'link':it.link]]
}

will result in something like :

[
[bar:[caption:BarCaption-2, image:BarImage-2, link:BarLink-2]],
[bar:[caption:BarCaption-1, image:BarImage-1, link:BarLink-1]],
[bar:[caption:BarCaption-0, image:BarImage-0, link:BarLink-0]],
[foo:[caption:FooCaption-2, image:FooImage-2, link:FooLink-2]],
[foo:[caption:FooCaption-1, image:FooImage-1, link:FooLink-1]],
[foo:[caption:FooCaption-0, image:FooImage-0, link:FooLink-0]]
]

If you have multiple items per each category you probably want to return the list of each.

def  bars = newList.findAll { it.containsKey 'bar'  }
def  foos = newList.findAll { it.containsKey 'foo'  }

[foos:foos,bars:bars] 

Upvotes: 2

Ed OConnor-Giles
Ed OConnor-Giles

Reputation: 716

If I understand your question correctly (I think you mean to put ':' instead of '=' for your maps) then I think the following will work. If new to Groovy, you might find the Groovy web console at http://groovyconsole.appspot.com/ useful. You can try snippets of code out easily, like the following:

def listOfMaps = [[category:'foo', caption:'stuff', something:'else'], [category:'bar', caption:'things', another:'thing']]
def mapOfMaps = [:]

listOfMaps.each { mapOfMaps += [(it.remove('category')) : it] }

assert mapOfMaps == [foo:[caption:'stuff', something:'else'], bar:[caption:'things', another:'thing']]

Upvotes: 0

Related Questions