Grails:域类中的派生字段

发布于 2024-12-06 13:58:54 字数 832 浏览 1 评论 0原文

假设我有一个域类branch,它有多个成员:

…
static hasMany = [ members:Member ];
…

现在假设我希望该分支的成员数量随时可用,以便将其显示在list中,并且view 操作,因此将该信息存储到域类本身的变量中也许是个好主意?

…
Integer memberCount = members.size();
static constraints = {
    memberCount(editable:false);
}
…

(这是正确的语法吗?) 编辑:这不是正确的语法。我无法评估成员列表的大小,因为它还不存在,并且 grails 会抱怨 size() 不适用于空对象。我还能尝试什么?

然而,由于 memberCount 现在是域类中的一个变量,因此可以在创建 Branch 时为其分配一个值(这是违反直觉的),并且它添加新成员后不会自动更新。

当然也可以通过不同的方式达到预期的结果。我可以操作 /Branch 目录中的 view.gsplist.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

故事和酒 2024-12-13 13:58:54

您可以将任何您不想保留的属性添加到 transients 静态列表中:

static transients = ['memberCount']

请参阅 手册中的此页

另外,这个 StackOverflow 问题回答了同样的问题


另外,还有一种更好的方法来处理派生属性可能是使用 派生GORM的属性特点

You can add any property you don't want persisted to the transients static list:

static transients = ['memberCount']

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文