Grails域类:多列的唯一约束

rai*_*198 46 orm grails unique-constraint grails-validation grails-domain-class

假设一个简单的Grails域类:

class Account {
    String countryId;

    String userName;

    String password;

    static constraints = {
        ...???...
    }
}
Run Code Online (Sandbox Code Playgroud)

要求用户名对于特定countryId是唯一的,因此在两列上必须存在唯一约束.如何在约束定义中表达这一点?

Jos*_*ore 84

userName(unique: ['countryId'])
Run Code Online (Sandbox Code Playgroud)

您可以在数组中包含尽可能多的其他属性,这些属性构成必须在用户名的"唯一"约束中考虑的其他属性.

因此,例如,如果您想userName在a中创建唯一的countryId,provinceId它将如下所示:

userName(unique: ['countryId', 'provinceId']
Run Code Online (Sandbox Code Playgroud)

  • @CarlosParraga,这只是同一件事的变种.同样的语法也可以与3.x之前的Grails版本一起使用. (3认同)
  • 在grails 3中,它写为“唯一的用户名:'countryId'” http://docs.grails.org/latest/ref/Constraints/unique.html (2认同)