Search code examples
grailsormmodelassociationsgrails-orm

What is the correct Grails ORM (GORM) implementation to use?


As a result of a change request I need to implement the correct ORM for my Grails application.

I currently have the following simple models and associations:

  • Agent

    static hasMany = [fees:Fee]
    
  • Fee

    static belongsTo = [agent:Agent]
    

However, now I need to implement the ability for a single Fee to be split amongst Agents. I ended up with the following:

Potential new models associations

  • Fee

    static hasMany = [agentfees:AgentFee]
    
  • Agent

    no associations ??
    
  • AgentFee

    static belongsTo = [fee:Fee]
    

In my mind an AgentFee would contain:

  • a reference to a Fee
  • a reference to an Agent
  • the Agent's % split of the fee (e.g. 80%)

So my question is. Should I also have an association between Agents and AgentFees i.e. something like:

  • Fee

    static hasMany = [agentfees:AgentFee]
    
  • Agent

    static hasMany = [agentfees:AgentFee]
    
  • AgentFee

    static belongsTo = [fee:Fee]
    static belongsTo = [agent:Agent]
    

But this just feels wrong with the multiple belongsTo in AgentFee. What is the best way to implement the notion of "Fee Splits" using GORM?

Thanks in advance,

John


Solution

  • It sounds like you are changing the relationship to a many-to-many. Here is the documentation for that: http://grails.github.io/grails-doc/latest/guide/GORM.html#manyToMany

    A many-to-many relationship needs a joining table at the DB level. However, you most likely don't need a domain for your joining table i.e. you don't need AgentFee. GORM will know to use a joining table.

    The only time you need a domain object for your joining table is if the joining table has additional columns beyond the ones needed to facilitate the many-to-many relationship. In this case you would create a domain for the joining table and then create two one-to-many relationships, one in each direction.