简体   繁体   中英

Grails undirectional hasMany createCriteria

The ability to use Pagination is the goal, however I'm not sure how to work with this. The relationship is unidirectional hasMany (seen below). As current it works fine without pagination (see Screenshot ), but to work with pagination I have to change the controller to use createCriteria. This is where I come into difficulty as its quite strange for the relationship.

Domain

Class Tag {

      String Tag
      User user

      static hasMany = [events: Event]
}

Controller

def searchTags() {
    println("TAG CONTROLLER  -  Params sent on click of tag are:  "+params.selected)
    def results = Tag.findByTagAndUser(params.selected, lookupPerson())

    //resultTotal is for show for the time being 
    [query: params.selected, results: results, resultTotal: 0]
}

GSP

<g:each in="${results.events}" status="i" var="t">
   .... ommited as unnessary
</g:each>

//Not working yet due to confusing createCriteria issue
<div class="pagination">
    <g:paginate total="${resultTotal}" />
</div>

I could do with a little guidance, this is what I'm thinking so far but I'm a little confused:

    def tagCriteria = Tag.createCriteria()
    def result = tagCriteria.list (max: 50, offset: 10) {
        eq("tag", params.selected)
        and {
            eq("user", lookupPerson())
        }
        //Not sure what to do at this point compared with the findByTagAndUser(params.selected, lookupPerson()).events  events being the hasMany relationship seen in domain
        events {

        }
    }

Give this a try.

def searchTags() {        
    def tagCriteria = Tag.createCriteria()
    def results = tagCriteria.list (max: 50, offset: 10) {

        eq("tag", params.selected)
        eq("user", lookupPerson())            

        projections {
            property("events")
        }
    }

    [query: params.selected, results: results, resultTotal: results.totalCount]
}

HQL version - The problem is you have to do the same query twice, but select the count(e)

Tag.executeQuery("""
Select e
from Tag t join t.events as e
where t.tag = :selected
and t.user = :user
""", [selected: params.selected, user: lookupPerson()], [max: 50, offset 10])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM