GORM 一对一关系,同时保留现有条目

GORM one to one relationship while keeping existing entries

在浏览了 GORM 的文档之后,我弄清楚了如何在对象之间创建一对一关系。但是,我还没有想出如何实现我想要的关系。我尝试创建的关系是一对一的关系,但保留以前的行条目用于历史目的。

例如,一辆汽车在其整个生命周期内可以有多个车主。如果我有 Car 和 Owner 域对象,我如何指定 Owners table 中给定 Car ID 的最新条目是正确的?

有很多不同的方法可以对此进行建模。 IMO,最灵活的方法之一是:

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]
}

例如,当 Ann 将她的汽车卖给 Bob 时,我们将 Ann 的 Ownership 记录的结束时间设置为销售时间,并为 Bob 保存一条新的 Ownership 记录,开始时间为-时间设置为销售时间。

如果获取汽车的当前所有者是我们经常需要执行的操作,我们可以在Car

中添加一个currentOwner方法
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)
  } 
}