开发者

Searching the values by using dynamic finders for two fields in grails

开发者 https://www.devze.com 2023-03-30 18:10 出处:网络
I am trying to search using dynamic finders for two fields: status and OpenOn (a date). render(view:\'list\', model:[incidentInstanceList:Incident.findAllByStatusIlikeAndOpenOnGreaterThan(\"closed\",

I am trying to search using dynamic finders for two fields: status and OpenOn (a date).

render(view:'list', model:[incidentInstanceList:Incident.findAllByStatusIlikeAndOpenOnGreaterThan("closed",new Date()-7,[sort:"id",order:"desc"])])开发者_开发百科 

The above query searches the last 7 days, but I want to search for "last week", not the last 7 days. How can I do this?


You may want something like this:

def lastWeek
use(org.codehaus.groovy.runtime.TimeCategory) {
    lastWeek = new Date() - 1.week
}

render(view:'list', model: [incidentInstanceList: Incident.findAllByStatusIlikeAndOpenOnGreaterThan( "closed", lastWeek, [sort:"id", order: "desc"])] )

UPDATE:

import java.util.Calendar
import groovy.time.TimeCategory

def roundToLastMonday(date) {
    Calendar cal=Calendar.getInstance();
    cal.setTime(date);
    cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) - cal.get(Calendar.DAY_OF_WEEK) + Calendar.MONDAY)
    cal.getTime()
}

def getLastWeekRange() {
    def startDate, endDate
    use(TimeCategory) {
      startDate = roundToLastMonday(1.week.ago)
      endDate = startDate + 1.week - 1.second
    }
    [startDate, endDate]
}

def range = getLastWeekRange()
def result = Incident.withCriteria {
    like ("status", "closed")
    between ("open", range[0], range[1])
}
render(view:'list', model: [incidentInstanceList: result]
0

精彩评论

暂无评论...
验证码 换一张
取 消