0
votes

i'm working on a multilingual grails application.

here is an example of my implementation of the multilingual feature:

the language domain

class Language {
    String name
   .....
}


class Category { 
    static hasMany = [translations : CategoryTranslation]
    ....
}


class CategoryTranslation {

    String name
    String description

    Language lang
    static belongsTo = [category:Category]

}

So category hasMany translations , 1 translation for each language , i want to sort categories by name , but the name is an attribute of the CategoryTranslation domain

what is the best way to implement sorting on the hasMany relations ?


EDIT :

the problem is that i have for each category multiple translations , example ,

cat1 --> have 3 translations ( arabic , english , and French )

cat2 --> have 3 translations ( arabic , english , and French )

cat3 --> have 3 translations ( arabic , english , and French )

def categoriesSortedByArabicName = Category.list(sort: "arabicName");
def categoriesSortedByEnglishName = Category.list(sort: "englishName"); 

first I thought to use , a transient property for each language but this method dont work with sort because the Hibernate translates the request to be processed with the database, and database simply doesn’t know what the field "arabicName" is anyway.

now i will try to add transient property using formula in static mapping

1
hasMany is on translations, and you want to sort categories. Question is not clear. Can you please rephrase last two lines? - dmahapatro
category hasMany translations , 1 translation for each language , i want to sort categories by english name , the name is an attribute of the CategoryTranslation domain - Hamila Mohamed Amine

1 Answers

1
votes

Associations are Set by default. You have to use SortedSet to maintain an order:

import java.util.SortedSet

class Category { 
    SortedSet translations
    static hasMany = [translations : CategoryTranslation]
}

//implement Comparable
class CategoryTranslation implements Comparable {
    String name
    String description
    Language lang

    static belongsTo = [category:Category]

    int compareTo(obj) {
        obj.name <=> this.name
    }
}

With Grails 2.4 (latest milestone) you get Groovy 2.3.0-SNAPSHOT, where you can use @Sortable AST transformation for CategoryTranslation as below:

import groovy.transform.Sortable

@Sortable(includes='name')
class CategoryTranslation {
    String name
    String description
    Language lang

    static belongsTo = [category:Category]
}