Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails - findAll Posts Created Today by User

I have a domain object.

class Post {
  User user
  String subject
  String body
  Date dateCreated
}

How do I go about this? Is straight GORM, HQL, or criteria the better way? I didn't know what kind of date manipulation ("today eq") would work in criteria.

like image 590
BuddyJoe Avatar asked Jun 23 '11 14:06

BuddyJoe


3 Answers

I would probably make a named query

class Post {
  User user
  String subject
  String body
  Date dateCreated

     static namedQueries = {
       todaysPosts {
          def now = new Date().clearTime()
          between('dateCreated', now, now+1)
       }
   }
}

Then you can use it like:

Post.todaysPosts.count()

or

Post.todaysPosts.list()
Post.todaysPosts.list(max: 10, offset: 5)

you can even do

Post.todaysPosts.findAllByUser(user)

Here is more on named queries

like image 151
sbglasius Avatar answered Dec 13 '22 15:12

sbglasius


Here's a criteria example:

// assuming future posts are disallowed
def posts = Post.withCriteria {
    eq('user', user)
    ge('dateCreated', new Date().clearTime())
}

// if you must accommodate future posts
def today = new Date().clearTime()
def posts = Post.withCriteria {
    eq('user', user)
    ge('dateCreated', today)
    lt('dateCreated', today.plus(1))
}
like image 30
Rob Hruska Avatar answered Dec 13 '22 14:12

Rob Hruska


I would use Grails Dynamic Finders to accomplish this:

Post.findAllByUserAndDateCreatedGreaterThanEquals(currentUser, new Date().clearTime())

Where "currentUser" is an instance of the current user

like image 20
Jon Quarfoth Avatar answered Dec 13 '22 15:12

Jon Quarfoth