Search code examples
grailsgrails-orm

GORM one to one relationship while keeping existing entries


After going over GORM's documentation, I've figured out how to create one-to-one relationships between objects. However, I haven't figured out how to go about enabling my desired relationship. The relationship I'm trying to create acts as a one-to-one, but keeps previous row entries for historical purposes.

For example, a Car can have multiple owners throughout its lifetime. If I have Car and Owner domain objects, how can I specify that the most recent entry in the Owners table for a given Car ID is the correct one?


Solution

  • There are lots of different ways to model this. IMO, one of the most flexible approaches is:

    class User {
      String name
      static hasMany = [ownerships: Ownership]
    }
    
    class Car {
      String name
      static hasMany = [ownerships: Ownership]
    }
    
    class Ownership {
      Date start
      Date end
      static belongsTo = [owner: User, car: Car]
    }
    

    For example, when Ann sells her car to Bob, we set the end-time of Ann's Ownership record to the time of sale and save a new Ownership record for Bob with the start-time set to the time of sale.

    If getting the current owner of a car is an operation we frequently need to perform, we could add a currentOwner method to Car

    class Car {
      String name
      static hasMany = [ownerships: Ownership]
    
      Ownership currentOwner() {
        // depending on how this method is used, you might want to
        // return the User instead of the Ownership
        Ownership.findByEndIsNullAndCar(this)
      } 
    }