3
votes

Lets say I have some simple classes for a twitter-like app:

  • User
  • Post

A user hasMany posts, and a post belongsTo a user.

Now, I'm trying to get a list of posts for a specific user in order of date.

I know I can get a list of all posts (for all users) by:

def posts = Post.list([sort: 'dateCreated', order: 'asc', max:10])

But to limit it to my particular user I need to reference the user I want and I am supposing that I need to switch from a static call to something like this where I reference the user first:

def user = User.findByUserId(userId)
def posts = user.posts

So now that will return a list of all the posts for that user, but how do organise that list so that they are ordered such as [sort: 'dateCreated', order: 'asc', max:10] to retrieve the first 10 in the correct order?

Or am I just going about this the wrong way?

2

2 Answers

7
votes

Update, based on conversation:

def user = User.findByUserId('steve')
def posts = Post.findAllByUser(user, [sort: 'dateCreated', order:'asc', max: 10])
4
votes

If you always want to retrieve the posts this way you can add a mapping block to the User class. Something like this:

static mapping = {
    posts sort:'dateCreated', batchSize:10
}