Queequeg
Queequeg

Reputation: 2894

Grails result set pagination

Suppose I have a class User with many Customers (marked with hasMany property). In the class Customer I mark the owner with belongsTo.

Now when I want to get user's customers I simply write User.read(params.id).customers

I want a pagination in my test project, so reading the entire customer list doesnt make much sense.. I'd use something like Customer.findAllByOwner but this method is such a method is not present..

How do I limit the result set of such a query then (offset and limit)?


package myapp

class User {
    ...
    static hasMany = [customers: Customer]
    ...
}

package myapp

class Customer {
    ...
    static belongsTo = User
    ...
}

Upvotes: 0

Views: 1196

Answers (2)

Anuj Arora
Anuj Arora

Reputation: 3047

The name of the property in the Customer that you are trying to access is 'user' instead of 'owner'. If you want the property name to be owner it should be:

static belongsTo = [owner : User]

You can paginate the result set of a dynamic finder by supplying a map containing the pagination parameters as the final parameter.

def customers = Customer.findAllByOwner(user, [max:params.max, 
                                     offset:params.offset)

Upvotes: 2

Daniel Woods
Daniel Woods

Reputation: 1029

Correct me if I'm wrong, but the idea in its most simplistic form here is that you want to get a list of Customers based off of the User object.

In that case, change your Customer domain class to something like...

class Customer {
   ...
   static belongsTo = [user: User]
   ...
}

Then, in your controller you can do something like:

def customerInstanceList = Customer.findAllByUser(User.get(params.id), [max: params.max, offset: params.offset])

Hope this helps.

Upvotes: 3

Related Questions