【发布时间】:2015-09-24 18:03:39
【问题描述】:
我正在尝试使用 CASE 语句按 GORM 查询进行排序。我所拥有的是带有state 列的视图,该值可以是州缩写或单词General。我将像这样运行查询
Dropdown.findByStateInList(['General','CA'], [sort: "stateOrderBy", order: "asc"]
但它返回一个错误
could not resolve property: stateOrderBy of: workspace.Dropdown
当我创建如下的域类时,stateOrderBy 的值是字符串 CASE WHEN state = 'General' THEN 2 ELSE 1 END 而不是 1 或 2,这就是我收到上述错误的原因。有没有办法评估我的 CASE 陈述?
@EqualsAndHashCode(includeFields=true)
class Dropdown implements Serializable {
String state
String dropDownNames
String sectionName
String prefix
Integer displayOrder
def stateOrderBy = "CASE WHEN state = 'General' THEN 2 ELSE 1 END"
static transients = [ "stateOrderBy" ]
static mapping = {
datasource 'plDropdown'
table 'view_AllTables'
id composite: ['state','sectionName','displayOrder']
state column:'state'
dropDownNames column:'DropDownNames'
sectionName column:'SectionName'
prefix column:'Prefix'
displayOrder column:'DisplayOrder'
stateOrderBy column:'stateOrderBy'
version false
}
}
编辑:General 列中总会有结果,但对于特定于州的查询可能没有结果。如果返回了特定于州的答案,我想使用该答案,否则为一般答案。
【问题讨论】:
-
有必要使用findBy吗?我认为您可以尝试使用 executeQuery:grails.github.io/grails-doc/latest/ref/Domain%20Classes/…
-
我可以使用它,但它会在很多地方使用,每次编写查询都是不必要的额外工作。
-
是的。但是您可以在您的域中的静态方法中定义它并在所有地方重用它。
标签: grails grails-orm