Query across multiple domain objects in Grails
I am building a "Recent Activity" page just to give some background. Basically this page will be a mash up of several different actions performed by the user. The problem is that this data spans across multiple (3 or so) domain object types all with different fields. All of the domains are associated with the User object but the associations differ.
The domains are UserPost, FriendRequest, and UserTask. Is there a way I can query all these domains, support pagination, and order by dateCreated? Would it be better to change my structure? An开发者_如何学编程y help would be great!
I have implemented similar feature for my web site and I come to the conclusion that it is better to add an Activity domain class that records all kind of activities. Let's say
class Activity {
Date dateCreated
String linkClassName
Long linkId
def getLink() { getClass().classLoader.loadClass(linkClassName).get(linkId) }
}
Then whenever you insert a new record in your UserPost, FriendRequest, and UserTask (or whatever), you create a new entry in Activity as well using afterInsert
GORM events as following:
def afterInsert = {
new Activity(linkClassName: this.class.name, linkId: this.id).save()
}
Once you have done this, you can retrieve your recent activities like this:
def activities = Activity.list(max: 5, sort:'dateCreated', order:'desc')
精彩评论