Grails get any of the children in a hasMany
Asked Answered
J

1

6

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()
Juncaceous answered 27/6, 2011 at 21:44 Comment(0)
D
9

thingies is a Collection, so you have everything from Collection at your disposal.

A simple way you might do this is:

def one = myInstance.thingies.asList().first()

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:

def one = myInstance.thingies.size() > 0 ? myInstance.thingies.asList().first() : null

Or, if you want to be super-concise at the expense of some readability, you can use this approach (courtesy John Wagenleitner):

def one = myInstance.thingies?.find { true }
Deepen answered 27/6, 2011 at 21:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.