tiktak
tiktak

Reputation: 1811

Grails gorm: queries with map

Having the following domain class:

class Word {
    Map translations
}

And instances in BootStrap:

def word1 = new Word().with{
    translations = [en:"game"]
    save(failOnError: true, flush: true)
}

def word2 = new Word().with{
    translations = [en:"life"]
    save(failOnError: true, flush: true)
}

What is the groovy way to get all words, where translation starts with startPart in some locale? For example:

def listWordsStartsWith(startPart, locale, params){
    def regexp = startPart+'%'
    def query = Word.where {
        //translations[locale] =~ regexp
    }
    def words = query.list(params)
    words
}

Upvotes: 3

Views: 1231

Answers (2)

ataylor
ataylor

Reputation: 66059

I don't think this is possible with GORM using a collection value for the translations field. I'd suggest the following alternate mapping:

class Word {
    static hasMany = [translations: Translation]
}
class Translation {
    static belongsTo = Word
    String key
    String value
}

Then the query would be something like this:

Word.createCriteria().list {
    translations {
        like('key', startPart+'%')
    }
}

Upvotes: 4

Nicolas Zozol
Nicolas Zozol

Reputation: 7038

The where wethod relies on Groovy SQL, where you have a very small subset of Groovy. It maps the SQL commands, but allow IDE controls on the properties and well formed syntax. Unfortunately, you cannot write all the Groovy inside (no function, few operators, no map, etc.).

Check the documentation to see what is accepted.

Upvotes: 1

Related Questions