[英]grails GORM derived properties
I have a field in my grails domain object that I want to be a derived field from other tables. 我的grails域对象中有一个字段,我想成为其他表的派生字段。 My domain looks like the following
我的域如下所示
class VotingTally{
int votesSource1
int votesSource2
int totalVotes
}
static mapping = {
totalVotes formula: (votesSource1.numOfVotes+ votesSource2.numOfVotes)
}
The error I get is 我得到的错误是
No such property: votesSource1 for class: org.grails.datastore.mapping.config.groovy.MappingConfigurationBuilder
First of all, formula
should be a string with SQL expression (you have Groovy expression). 首先,
formula
应该是带有SQL表达式的字符串(您具有Groovy表达式)。 Like: 喜欢:
static mapping = {
totalVotes formula: 'numOfVotes1 + numOfVotes2'
}
But in your case you want to calculate value from joined tables, and that's not possible. 但是在您的情况下,您想从联接表中计算值,而这是不可能的。 You just cannot add
JOIN
from here. 您只是不能从此处添加
JOIN
。
Seems that you have only one way - load it from the code: 似乎只有一种方法-从代码中加载它:
static transients = ['totalVotes']
int getTotalVotes() {
VotesSource.get(votesSource1).numOfVotes + VotesSource.get(votesSource2).numOfVotes
}
As Andrew von Dollen mentioned, you still could use a formula, through the use of sub selects, but it's not always the best option. 正如安德鲁·冯·多伦(Andrew von Dollen)所提到的那样,您仍然可以通过使用子选择来使用公式,但这并不总是最好的选择。 Plus, your domain needs to have a way to relate the two vote sources (typically as a one-to-many or a many-to-many relation).
另外,您的域需要有一种方法来关联两个投票源(通常是一对多或多对多关系)。 It amounts to something like:
它相当于:
static mapping = { totalVotes formula: '((select count(*) from vote_source_1 vs1 where vs1.source_id = id) + (select count(*) from vote_source_2 vs2 where vs2.source_id = id))' }
note, the above likely won't work for you as is. 请注意,以上内容可能对您不起作用。 It is dependent on your particular DB engine and your domain model linking the vote sources via some shared id on which to perform the join.
它取决于您特定的数据库引擎和域模型,该域模型通过一些共享ID链接投票源,并在该共享ID上执行联接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.