tags:

views:

601

answers:

2

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  A: 

Update, based on conversation:

def user = User.findByUserId('steve')
def posts = Post.findAllByUser(user, [sort: 'dateCreated', order:'asc', max: 10])
Robert Munteanu
That's good, but is there anyway I can limit the DB retrieval to a batch of 10? Or do I have to retrieve all and then manipulate in memory?
Stevo
I _think_ you should be able to use `GORM` to retrieve posts using something similar to Post.findByUser(user, [sort: 'dateCreated', order:'asc', max: 10]). See http://grails.org/doc/1.1.x/ref/Domain%20Classes/findAllBy.html
Robert Munteanu
Sweeeeet! def user = User.findByUserId('steve') def posts = Post.findAllByUser(user, [sort: 'dateCreated', order:'asc', max: 10])Thanks!
Stevo
Accepted for Robert's comment afterwards.
Stevo
+3  A: 

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
}
Dave Klein
Good Call Dave :-) http://grails.org/doc/1.1.1/guide/5.%20Object%20Relational%20Mapping%20(GORM).html#5.5.3%20Default%20Sort%20Order Keep in mind the order doesn't work on the mapping dsl yet:http://jira.codehaus.org/browse/GRAILS-3778
Colin Harrington