Grails - findAll Posts Created Today by User

£可爱£侵袭症+ 提交于 2019-12-07 05:31:57

问题


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.


回答1:


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




回答2:


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))
}



回答3:


I would use Grails Dynamic Finders to accomplish this:

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

Where "currentUser" is an instance of the current user




回答4:


String sqlQuery = "SELECT * FROM Post p WHERE p.dateCreated  = NOW()"
def e = Post.executeQuery(sqlQuery)



回答5:


For the sake of completeness, this is a query written in HQL:

def yourUser = User.get(1)
def results = Post.executeQuery( "select * from Post a where a.user = :user and a.dateCreated >= :dateCreated", [user : yourUser , dateCreated : new Date().clearTime()] );

@Tyndall: there are many answers for this question, just take one that you feel comfortable with.



来源:https://stackoverflow.com/questions/6456061/grails-findall-posts-created-today-by-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!