我有以下域類:Grails的格姆約束問題
class Metric {
String name
float value
static belongsTo = [Person,Corporation]
static indexes = {
name()
}
}
我如何添加一個約束這樣的人,公司和名稱是獨一無二的?
謝謝。
我有以下域類:Grails的格姆約束問題
class Metric {
String name
float value
static belongsTo = [Person,Corporation]
static indexes = {
name()
}
}
我如何添加一個約束這樣的人,公司和名稱是獨一無二的?
謝謝。
我認爲這應該工作..將此添加到公制。如果你願意,顯然你可以忽略這些可空的。
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)
但是,可能存在用於不同公司或團體的相同名稱。 – 2010-06-07 01:53:03
下面是類似情況的鏈接,略有不同。但非常接近。可以給你一個關於如何做到這一點的好主意。
http://johnrellis.blogspot.com/2009/09/grails-constraints-across-relationships.html
在我開始與我的答案,我想告誡說,與Grails的1.2.x版本(可能是1.3.x中也一樣)化合物的唯一約束被打破,如果任何一個值,可以爲null。如果你沒有獨特的行爲不能生活,你可以使用自定義驗證來實現。請參閱:https://cvs.codehaus.org/browse/GRAILS-5101
在名稱,人員和公司範圍內完成公制域名的正確方法是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。
在上面的例子中,名字必須在人和公司是唯一的;人的名字和公司必須是獨一無二的,最後,公司的名稱和人員必須是唯一的。
確保你想要這個。一個人可能會在不同的時間爲不同的職位工作。 – 2010-06-05 02:42:33