简体   繁体   中英

grails GORM derived properties

I have a field in my grails domain object that I want to be a derived field from other tables. 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). 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.

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. 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.

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.
  • 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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