我的域类如下所示:
class UserEvent {
User user
Event event
boolean isAttending
}
生成的数据库表看起来具有以下列:
[ID , EVENT_ID, USER_ID , IS_ATTENDING ]
我有事件对象和用户对象的唯一ID(user_id)。 我想仅使用此数据创建新的 UserEvent 对象,而不加载 User 对象,它可能看起来像这样:
def userEvent = new UserEvent(user:['id':user_id],isAttending: true, event: event)
我尝试了很多方法,但没有找到解决方案。我认为这绝对是可能的,因为它是通过 Controller 中的参数以类似的方式完成的,其中仅包含关联对象的 id:
def userEvent= new UserEvent(params)
我期待找到解决方案。谢谢。
最佳答案
当你说“不加载用户对象”时,你可以这样做:
def userEvent = new UserEvent(user:User.load(user_id), isAttending: true, event: event)
与 get
不同,load
方法不访问数据库。相反,它创建一个代理对象,仅在第一次访问非 id
属性时从数据库获取数据。
关于Grails 域类构造函数使用 id 而不是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11668339/