简体   繁体   English

获取GORM派生的属性

[英]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上执行联接。

pros: 优点:

  • you can sort and query on the property value just like any other property 您可以像其他任何属性一样对属性值进行排序和查询
  • avoids creating a denormalized database 避免创建非规范化的数据库
  • puts the processing costs in the DB (could also be a con...) 将处理成本放入数据库中(也可能是一个缺点...)

cons: 缺点:

  • can introduce a DB Engine type dependency if using non-standard SQL. 如果使用非标准SQL,则会引入DB Engine类型依赖关系。
  • will not give accurate values on new or dirty instances since the property isn't valid or updated until the instance is saved (and possibly flushed) 在属性被保存或刷新之前,该属性无效或更新,因此不会在新实例或脏实例上提供准确的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM