问题
I have two domains that are connected with one-to-many relation - One User may have many Associations. I want to view all associations that belong to this user. I'm using scaffolding plugin. So code that should return list of Associations in AssociationController looks lile this:
def index(Integer max) {
respond Association.list(params), model:[associationInstanceCount: Association.count()]
}
And on the User view page I have the following code:
<g:form controller="Association" >
<fieldset class="buttons">
<g:hiddenField name="user.id" id="user.id" value="${userInstance.id}"/>
<g:actionSubmit class="list" action="index" value="${message(code: 'default.list.label', default: 'Show Associations')}"/>
</fieldset>
</g:form>
When I press this actionSubmit user.id
is sent with the request and it is within params map (I checked it with debug) but for some reason Association.list(params)
returns all Associations (for all users) despite the fact that I'm using this user.id within params. A also tried rename user.id
to just user
and it didn't work either. Seems like this .list() should be used only for sorting or I'm doing something wrong. Can you help me with this please? Thank you!
回答1:
To clarify the given answer: list( params )
returns ALL results for the domain object, and accepts only sorting (order by) and view-port (limit/offset) parameters. It does not provide any where
clause (well, apart from discriminator
-column)
UPDATE:
you can use findAllBy*
:
Association.findAllByUserId( params.long( 'user.id' ), params )
or criteria
if you need to make your query more complex:
Association.withCriteria{
eq 'id', params.long( 'user.id' )
maxResults params.int( 'max' ) ?: 10
firstResult params.int( 'offset' ) ?: 0
if( params.sort && params.order ) order params.sort, params.order
}
回答2:
According to Grails documentation, list does not take an id as parameter.
Seeing your max, it would be Association.list(max: max)
and for what you want, it is something like:
Association.findAllByUserId(params.id, [max: max])
Where params.id
contains the id
of the wanted user (or params['user.id']
).
More on findAllBy...
回答3:
Not sure about the previous response but :
Association.where {
user {
eq 'id', params['user.id']
}
} .list()
You can add params to list call if you use pagination.
Another solution :
def index(User user) {
respond user.associations, , model:[associationInstanceCount: user.associations.size()]
}
But you'll have to name your param 'id' It mostly depends on how you have designed your domain objects and what's your goal here.
来源:https://stackoverflow.com/questions/25425887/grails-domain-class-list-method-with-params