简体   繁体   中英

Grails domain class query - how can I find by fields that link to another domain class?

Lets say I have two domain classes:

class User {
  String name
  Role role
}

class Role {
  String name
  static belongsTo = [user: User]
}

and I create some records:

def r1 = new Role(name: "role1").save()
def r2 = new Role(name: "role2").save()
new User(name: "user1", role: r1).save()
new User(name: "user2", role: r2).save()
new User(name: "user3", role: r1).save()

How can I now select my users by role? I would expect to be able to do one of the following:

def role = Role.findByName("role1"); //returns a Role with [ id:1 name:"role1" ]
User.findAllByRole(role) //returns null
User.findAllByRole(new Role(name: "role1")) //returns null
User.findAllByRole(role.id) //returns null
User.findAllByRole(id: role.id) //returns null

Is it possible for a domain class to find other associated domain classes using the dynamic find* methods? I can do it using namedQueries, but id rather not because I dont want to have to write them out for every relationship I have between domain classes

It appears that the findBy* and findAllBy* methods DO work, if you retrieve the object you need to find beforehand. It appears that it must be an exact (non-stale?) reference to an object in the database, so you cannot create a new object that "looks" like the object you want to find by, it actually has to be that object.

So, in order to find all the Users with the role of "role1":

def role = Role.findByName("role1")
def users = User.findAllByRole(role)
for (def user in users) {
 println("User ${user.name} matched the query, with role: ${user.role.name}")
}
//prints:
//User user1 matched the query, with role role1
//User user3 matched the query, with role role1

User.findAllByRole(role) doesn't work on unit tests. I believe that's what confused you, Erin.

It seems Querying Associations isn't possible under unit tests. I've tried it this way: User.findAllByRole(role.id) and it works although not outside unit tests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM