2012-11-19 9 views
6

Voglio integrare sort, order, max e offset in una query findAll. Il seguente funziona bene:Grails findAll con ordinamento, ordine, max e offset?

def books = Book.findAll("from Book as b where b.approved=true order by b.dateCreated desc", [max: max, offset: offset]) 

Ma quello che voglio è:

def books = Book.findAll("from Book as b where b.approved=true", [sort: 'dateCreated', order: 'desc', max: max, offset: offset]) 

Questo non funziona. Come devo riscrivere questo?

risposta

7

HQL non supporta tipo e l'ordine come parametri, quindi è necessario includere "l'ordine dal" come parte dell'espressione HQL

def books = Book.findAll("from Book as b where b.approved=true" 
    + " order by b.dateCreated desc", [max: max, offset: offset]) 

(o in questo caso basta usare Book.findAllByApproved(true, [...]) invece di HQL) .

Quindi, se il tipo e l'ordine sono variabili è necessario un trucco come

def books = Book.findAll("from Book as b where b.approved=true" 
    + (params.sort ? " order by b.${params.sort} ${params.order}" : ''), 
    [max: max, offset: offset]) 
+0

Questo non risponde la domanda. Come posso includere ordinare e ordinare come variabile in questa query? – confile

+0

@userWebMobile vedi modifica. –

+0

perché usi: ''? – confile

6

Utilizzando un dove query funziona per me:

def books = Book.where{approved == true}.list(sort: 'dateCreated', order: 'desc', max: max, offset: offset)

O con params direttamente dalla pagina:

def books = Book.where{approved == true}.list(params)

0

Utilizzo di "findAllBy" perché supporta l'ordinamento e l'ordinamento.

def results = Book.findAllByTitle("The Shining", 
      [max: 10, sort: "title", order: "desc", offset: 100]) 

Fare clic su here per dettagli.

0

Suppongo che stiate chiamando a prendere l'elenco di libri in un controller o in una classe di servizio.

Se si sta chiamando da un'azione del controller, una variabile magica "params" è già disponibile. Per esempio, se si richiede la pagina come segue

book/list?max=10&offset=2 

poi "params" avranno già quei valori mappati automagicamente.

È possibile aggiungere altri elementi alla mappa params come segue

params.sort = "dateCreated" 
params.order = "desc" 

Una volta che avete costruire i params, se lo desideri, quindi è possibile utilizzare Grails query dinamica come segue

def books = Book.findAllByApproved(true, params) 
// use "books" variable as you wish 
Problemi correlati