代码之家  ›  专栏  ›  技术社区  ›  xain

格雷尔斯的戈姆约束问题

  •  1
  • xain  · 技术社区  · 15 年前

    我有以下域类:

     class Metric {
    
       String name
       float value
    
       static belongsTo = [Person,Corporation]
    
       static indexes = {
        name()
     }
    }
    

    如何添加一个约束,使人员、公司和名称是唯一的?

    谢谢。

    3 回复  |  直到 15 年前
        1
  •  2
  •   Steven Dorfmeister    15 年前

    我想这应该管用。把这个加到公制上。显然,如果需要,可以忽略空值。

    static constraints = {
            name(blank:false)
            corporation(nullable:false)
            person(nullable:false)
    
            name(unique:['corporation','person'])
        }
    

    我用这个集成测试进行了测试,它似乎可以工作。

    def newCorp = new Corporation(name:"Corporation1")
    newCorp.save()
    def newPerson = new Person(name:"Person1")
    newPerson.save()
    
    def newMetric = new Metric(name:"Metric1",corporation:newCorp,person:newPerson)
    newMetric.save()
    
    newMetric = new Metric(name:"Metric1",corporation:newCorp,person:newPerson)
    newMetric.save()
    
    assertTrue (Metric.list().size == 1)
    
        2
  •  0
  •   Gregg    15 年前

    这是一个类似情况的链接,略有不同。但很接近。可能会给你另一个好主意如何做到这一点。

    http://johnrellis.blogspot.com/2009/09/grails-constraints-across-relationships.html

        3
  •  0
  •   Ben Doerr    15 年前

    在继续我的答案之前,我想警告一下,如果任何一个值可以为空,那么grails 1.2.x(也可能是1.3.x)的复合唯一约束就会被破坏。如果没有独特的行为你无法生存,你可以使用自定义验证来完成这一技巧。见: https://cvs.codehaus.org/browse/GRAILS-5101

    实现metric域类的正确方法是 unique 在姓名、个人和公司内。

    class Metric {
    
      String name
      float value
      Person person
      Corporation corporation
    
      static belongsTo = [person: Person, corporation: Corporation] 
    
      static indexes = {
        name()
       }
    
      static constraints = {
        name(unique:['person', 'corporation'])
        person(unique:['name', 'corporation'])
        corporation(unique:['name', 'person'])
      }
    }
    

    你需要将个人和公司称为你的模型的成员。如果不关心级联删除行为,甚至可以删除静态belongsto。

    在上面的例子中,名字在人和公司中必须是唯一的;人在名字和公司中必须是唯一的,最后公司在名字和人中必须是唯一的。