using createCriteria with order based on a belongsTo property
-
02-07-2021 - |
Question
I have the next scheme:
class UserProfile {
String title
String firstName
String lastName
static belongsTo = [user:User]
static constraints = {
user nullable:true , unique:true
title nullable:true, blank:true
firstName blank:false
lastName nullable:true, blank:true
}
}
class User {
String username
String password
boolean enabled
String email
static constraints = {
username size:6..40, blank:false, nullable: false, unique: true
email email:true, size:6..40, blank:false, nullable: false, unique: true
password size:5..64, password:true, blank:false, nullable: false
}
String toString(){username}
}
I need a list of UserProfile
ordered by the email that has the user!
I try:
UserProfile.createCriteria().listDistinct({
if(params.orderBy){
if(params.orderBy=="email"){
//the exception says that the element has no such property to both cases
order("user.email", ascDesc)
//order("email", ascDesc)
}else{
order("${params.orderBy}", ascDesc)
}
}
})
so when I want to order by the email the exception says that the element has no such property to both cases. Note: ascDesc
is a variable String
it can be asc
or desc
La solution
If you add
createAlias('user', 'u')
to the top of your criteria closure then you should be able to order by 'u.email'
.
Autres conseils
if (params.orderBy == "email") {
user {
order ("email", ascDesc)
}
}
should work too without manual alias creation
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow