Grails 获取 hasMany 中的任何子级
我有一个域类,其中有许多其他域类。我想要任何一个孩子,不在乎是哪一个。例如,
class MyDomainClass {
static hasMany = [thingies:OtherDomainClass]
}
我可以用愚蠢的方式做到这一点,例如:
def findOne
myInstance.thingies.each{
findOne=it
}
但是有更好的方法吗,例如:
def findOne = myInstance.thingies.grabTheMostConvenientOne()
I have a domain class which has many of another domain class. I want any one of the children and don't care which. Example
class MyDomainClass {
static hasMany = [thingies:OtherDomainClass]
}
I can do this the stupid way like:
def findOne
myInstance.thingies.each{
findOne=it
}
But is there a better way like:
def findOne = myInstance.thingies.grabTheMostConvenientOne()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
thingies
是一个集合,因此您拥有 收藏供您使用。您可以执行此操作的一个简单方法是:
但是,您可能希望首先确保集合实际上具有一些元素。文档没有明确说明如果列表为空,
first()
会抛出 IndexOutOfBoundsException,但我感觉它仍然可能会抛出。如果是这种情况,您可能想要:或者,如果您想以牺牲一些可读性为代价变得超级简洁,您可以使用这种方法(由 John Wagenleitner 提供):
thingies
is a Collection, so you have everything from Collection at your disposal.A simple way you might do this is:
However, you probably want to make sure the collection actually has some elements first. The documentation doesn't explicitly say that
first()
throws an IndexOutOfBoundsException if the list is empty, but I have a feeling it still might. If that's the case, you probably want:Or, if you want to be super-concise at the expense of some readability, you can use this approach (courtesy John Wagenleitner):