如何迭代groovy中的列表并为每个对象添加属性 [英] How to iterate over a list in groovy and add property for each object
问题描述
我有这样的事件列表:
events = Events.all
Events
通过类 UserEvents
与 Users
具有多对多关系。模仿方法spring-security-plugin :
我想知道 User
是否参加 Event
,我可以这样做:
UserEvent.get (currentUserId,eventId)
问题
如何在列表 events
的所有元素上做到这一点,以便在我的视图层中可以轻松找出 currentUserId
将会发生什么事?
您可以查询所有关联的用户
s用于事件 code>像这样:
def user = ...
def events = UserEvent.findAllByUser(user ).event
这是一个相当高效的查询,因为它执行的SQL类似于
select * from user_event where user_id =?
然后加载每个事件
。这是N + 1,因为它会逐个加载每个事件,因此您可以通过以下方法更高效地完成此操作:
def eventIds = UserEvent.findAllByUser(user).eventId
def events = Event.getAll(eventIds)
第一行只是使用与上面相同的SQL获取事件id,然后第二行运行SQL,如
select * from event (?,?,?,...)
I have a list of events like so:
events = Events.all
Events
have a many-to-many relationship with Users
via class UserEvents
modeled after the approach from spring-security-plugin:
I would like to find out whether a User
is attending an Event
and I can do that by running this:
UserEvent.get(currentUserId, eventId)
Question
How can I do this over all the elements of my list events
so that in my view layer I can easily find out whether currentUserId
is going to the event?
You can query for all of the associated User
s for an Event
like this:
def user = ...
def events = UserEvent.findAllByUser(user).event
This is a fairly efficient query since it executes SQL similar to
select * from user_event where user_id=?
and then loads each Event
. This is N+1 though since it loads each Event individually, so you can do it more efficiently with this:
def eventIds = UserEvent.findAllByUser(user).eventId
def events = Event.getAll(eventIds)
The first line just gets the event ids using the same SQL as above, then the second line runs SQL like
select * from event where id in (?, ?, ?, ...)
这篇关于如何迭代groovy中的列表并为每个对象添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!