Grails:域类中的派生字段
假设我有一个域类branch
,它有多个成员:
…
static hasMany = [ members:Member ];
…
现在假设我希望该分支的成员数量随时可用,以便将其显示在list
中,并且view
操作,因此将该信息存储到域类本身的变量中也许是个好主意?
…
Integer memberCount = members.size();
static constraints = {
memberCount(editable:false);
}
…
(这是正确的语法吗?) 编辑:这不是正确的语法。我无法评估成员列表的大小,因为它还不存在,并且 grails 会抱怨 size() 不适用于空对象。我还能尝试什么?
然而,由于 memberCount
现在是域类中的一个变量,因此可以在创建 Branch
时为其分配一个值(这是违反直觉的),并且它添加新成员
后不会自动更新。
当然也可以通过不同的方式达到预期的结果。我可以操作 /Branch
目录中的 view.gsp
和 list.gsp
,添加一些额外的
基本上,我认为我正在寻找的是某种方式来告诉 grails 某个变量是派生的,不应该由用户设置,而是在必要时进行更新。有这样的办法吗?
Suppose I have a domain class branch
which has several members:
…
static hasMany = [ members:Member ];
…
Now suppose I want to have the number of members of that branch readily available, to have it displayed in the list
and view
actions, so perhaps storing that information into a variable in the domain class itself would be a good idea?
…
Integer memberCount = members.size();
static constraints = {
memberCount(editable:false);
}
…
(Is this the correct syntax?) Edit: This is not the correct syntax. I cannot assess the size of the members list, as it doesn’t exist yet and grails will complain about size() not being applicable to null objects. What else could I try?
However, as memberCount
is now a variable in the domain class, it is possible to assign a value to it upon creation of the Branch
(which is contra-intuitive) and it will not be updated automatically once a new Member
is added.
It is of course possible to reach the desired result in a different way. I could manipulate the view.gsp
and list.gsp
in the /Branch
directory, add some additional <td>
s there etc. But that does not seem very elegant to me.
Basically, I think what I am looking for is some way to tell grails that a certain variable is derived, should not be setable by the user, but update whenever necessary. Is there such way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将任何您不想保留的属性添加到
transients
静态列表中:请参阅 手册中的此页
另外,这个 StackOverflow 问题回答了同样的问题
另外,还有一种更好的方法来处理派生属性可能是使用 派生GORM的属性特点
You can add any property you don't want persisted to the
transients
static list:See this page in the manual
Also, this StackOverflow question answers the same question
Also, a better way to do derived properties may be to use the Derived Properties feature of GORM