1
votes

I'm trying to create GORM criteria query filtering by a property of sub-entity. So there are such entities:

class PaymentEntry {

  static hasOne = [category: PaymentCategory]

  static constraints = {
    category(nullable: true)
  }

  // other stuff
}

class PaymentCategory {

  static hasMany = [payments: PaymentEntry]

  // other stuff  
}

Now I'm trying to select PaymentEntries, with specific categories. I was trying something like this:

def c = PaymentEntry.createCriteria()

def res = c {
  'in'("category", categories)
}

categories here is a list of PaymentCategory entities, selected earlier.

Unfortunately, this fails. Grails throws NoSuchMethodException.

2
Which Grails version? - Michal_Szulc

2 Answers

1
votes

You should have inList. Try this:

def res = c {
  inList("category", categories)
}
0
votes

There are a number of problems. hasOne is meant for one-to-one associations, yet you actually have a one-to-many. So the first step is to fix the associations, possibly like this:

class PaymentEntry {

  static belongsTo = [category: PaymentCategory]

  static constraints = {
    category(nullable: true)
  }

  // other stuff
}

class PaymentCategory {

  static hasMany = [payments: PaymentEntry]

  // other stuff  
}

Next, once you have a criteria instance, you need to call one of its methods, such as list(), to build and execute your query.

def c = PaymentEntry.createCriteria()

def res = c.list {
  'in'("category", categories)
}  

A shorter version of the same thing is...

def res = PaymentEntry.withCriteria {
  'in'("category", categories)
}  

Both in() and inList() are available to you, as long as you quote in as you did, since it's a Groovy keyword. You can read more about criteria queries here.