Reputation: 3651
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
Upvotes: 0
Views: 1899
Reputation: 1
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.
Upvotes: 0
Reputation: 35951
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
}
Upvotes: 1