Grails控制器中字段之间的级联更新

时间:2014-04-26 12:33:55

标签: grails gorm grails-controller

我有一个名为Merchant的类,它有两个相关的字段(在域和数据库中都相关),如下所示:

/**
*This class keeps information about a merchant
*/
class Merchant{

...

//The email of the merchant which is also 
//as the username property of the login field
String email
//The login credentials of the merchant
UserLogin login

...

}

Userlogin类也是这样定义的

/**
*This class is used to hold the login credentials 
* of a Customer, Admin or "Merchant"
*/
class UserLogin{

...

//The username used to Login
String username
//The password used to Login
String password

...

}

现在的问题是,在添加新商家期间,还会使用他的电子邮件作为用户名为商家生成登录信息。

我正在使用动态脚手架,但只想添加代码以更新商家的userLogin的用户名字段。

现在,当商家的电子邮件更新时,登录的用户名不会更新,我通常会在登录后使用用户名来获取相应的商家。

  • 如何在更改电子邮件时添加一个小代码段来更新商家的登录凭据(用户名),或者我可以在任何方式创建商家电子邮件和其登录用户名之间的数据库更新级联。(我可以在我覆盖的控制器操作中使用super.update()吗?

1 个答案:

答案 0 :(得分:1)

在您的商家域类中,您可以添加以下方法来拦截更新事件,如果电子邮件属性已更改,则更新相应的用户名。在我的头顶,它看起来像这样:

def beforeUpdate() {
    if (this.getDirtyPropertyNames().contains('email')) {
        this.login.username = this.email
    }
}

您可以在documentation中找到有关GORM事件及其挂钩的更多信息。