通过 constrainedProperty 访问 Grails 中的唯一约束
Access unique constraint in Grails through constrainedProperty
我在访问 Grails 域中定义的唯一约束时遇到问题。 Here's an example from the official Grails documentation(稍作编辑以具有唯一约束):
class User {
String firstName
String middleName
static constraints = {
firstName blank: false, nullable: false
middleName unique: true, nullable: true
}
}
在 Grails 3.1.9 上:
此代码有效:User.constrainedProperties.firstName.blank
此代码无效:User.constrainedProperties.middleName.unique
我收到此错误:
groovy.lang.MissingPropertyException: No such property: unique for class: grails.validation.ConstrainedProperty
有什么方法可以判断是否设置了此约束,类似于检查是否设置了 "blank" 约束?谢谢
更新:这是我尝试使用评论中建议的代码时得到的结果(空白与可为空的唯一区别)。 hasAppliedConstraint 工作正常,但 getAppliedConstrait 没有。我假设我在某个地方犯了一个愚蠢的错误?
Condition not satisfied:
User.constrainedProperties.middleName.getAppliedConstraint('unique')
| |
| null
[ConstrainedProperty@20344ed7User'middleName'middleNamemap['nullable' -> [NullableConstraint@4a2415c5true], 'unique' -> [UniqueConstraint@7115e8atrue]]]
以下是最终对我有用的方法。不知道为什么。
User.constrainedProperties.middleName.getAppliedConstraints().find {it.name == 'unique'}.properties.parameter
您的代码有效,因为 User.constrainedProperties
returns Map
具有键 domainPropertyName
和值 ConstrainedProperty
。在您的情况下,您获得 属性 middleName
的 ConstrainedProperty
方法 getAppliedConstraints()
其中 returns 所有约束都应用于 middleName
.
你可以做得更好:
User.constrainedProperties.middleName.getAppliedConstraint('unique').parameter
我在访问 Grails 域中定义的唯一约束时遇到问题。 Here's an example from the official Grails documentation(稍作编辑以具有唯一约束):
class User {
String firstName
String middleName
static constraints = {
firstName blank: false, nullable: false
middleName unique: true, nullable: true
}
}
在 Grails 3.1.9 上:
此代码有效:User.constrainedProperties.firstName.blank
此代码无效:User.constrainedProperties.middleName.unique
我收到此错误:
groovy.lang.MissingPropertyException: No such property: unique for class: grails.validation.ConstrainedProperty
有什么方法可以判断是否设置了此约束,类似于检查是否设置了 "blank" 约束?谢谢
更新:这是我尝试使用评论中建议的代码时得到的结果(空白与可为空的唯一区别)。 hasAppliedConstraint 工作正常,但 getAppliedConstrait 没有。我假设我在某个地方犯了一个愚蠢的错误?
Condition not satisfied:
User.constrainedProperties.middleName.getAppliedConstraint('unique')
| |
| null
[ConstrainedProperty@20344ed7User'middleName'middleNamemap['nullable' -> [NullableConstraint@4a2415c5true], 'unique' -> [UniqueConstraint@7115e8atrue]]]
以下是最终对我有用的方法。不知道为什么。
User.constrainedProperties.middleName.getAppliedConstraints().find {it.name == 'unique'}.properties.parameter
您的代码有效,因为 User.constrainedProperties
returns Map
具有键 domainPropertyName
和值 ConstrainedProperty
。在您的情况下,您获得 属性 middleName
的 ConstrainedProperty
方法 getAppliedConstraints()
其中 returns 所有约束都应用于 middleName
.
你可以做得更好:
User.constrainedProperties.middleName.getAppliedConstraint('unique').parameter