【问题标题】:many-to-many in grails is not saving records in the relationship tablegrails中的多对多没有在关系表中保存记录
【发布时间】:2013-02-18 17:13:54
【问题描述】:

ColorShade 之间存在多对多关联。 Color 有多种颜色,Shades 有多种颜色。

我是这样建模的:

class Color {
  static hasMany = [shades: Shade]
  String name
}

class Shade {
  static belongsTo = Color
  static hasMany = [colors: Color]
  String name
}

但是,当我运行以下代码时:

new Color(name: "Red").addToShades(new Shade(name: "light")).save()

它只将记录保存在Color 表和Shade 表中,但不保存在Color_Shades 表中,Color_Shades 表本质上是两者之间的连接表。

我做错了吗?这就是我从docs 中理解的:

【问题讨论】:

    标签: grails many-to-many grails-orm


    【解决方案1】:

    我不确定为什么没有填充您的表,但在 this talk 中有一个关于 Burt 的建议,关于使用这种类型的多对多的性能。解决方案是使用中间类:

    class ColorShade implements Serializable {
    
      Color color
    
      Shade shade
    
      //implement hashcode & equals!
      //and also implement helpers like removeAll, remove, create and get.
    
      static mapping = {
        id composite: ['color','shade']
        table 'Color_Shades'
        version false
      }
    }
    

    您可以在Spring Security Core plugin 中看到一个示例类。

    【讨论】:

    • 我将如何保存与此的关系?
    • 查看spring安全链接中的static create()。实现类似的东西并调用ColorShade.create(colorInstance, shadeInstance)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    相关资源
    最近更新 更多