如何在Grails中保存控制器类中的外键



我是Groovy和Grails的新手。我不知道如何将外键保存到子表中。我有两个名为Person和Telephone的域类。我曾试图保存,但它不起作用。请帮帮我。

个人.groovy

class Person {
    String name
        String password        
    static constraints = {
        name(blank:false)
                password(blank:false)
    }
    static hasMany = [telephone:Telephone]
    @Override
    public String toString() {
        // TODO Auto-generated method stub
    name
    }
}

电话.groovy

class Telephone {
    String number
    Person person
    static constraints = {
        number(blank:false)
        person()
    }
    static belongsTo = [person:Person]
    @Override
    public String toString() {
        // TODO Auto-generated method stub
    number
    }
}

存储在会话变量中的loggin人员Id。

session.setAttribute("user_id")

然后我试着保存号码。

TelephoneController.groovy

class TelephoneController {
     def index() {
        redirect(action:'create')
         }
    def create(){
    }
def save(){
        def number=new Telephone(params)
        int user_id=Integer.parseInt(session.getAttribute("user_id").toString())
                params.person=user_id       
        if(!number.hasErrors() && number.save()){
            println "save"
            flash.toUser="Person Details [${number.number}] has been added."
            redirect(view:'create')
        }
    }
}

但它不起作用。请帮帮我。

我同意第一个答案。你把代码搞得太复杂了。如果你只想为一个人存储很多电话号码,这样的东西就足够了:

class Person {
    String name
    String password
    static hasMany = [phoneNumbers:String]
    static constrains = ...
}

基本上,您不需要另一个域类来只存储Person的数字列表。然后在控制器中,您需要:

    def save() {
        int user_id = session['user_id'] // no need to parse, Groovy will handle
        def user = Person.get(user_id) // you need to fetch the Person from database (the same applies when using additional Telephone)
        user.phoneNumbers << params.newNumber // the << operator acts here like add(String) method
        user.save()
    }

如果决定使用另一个电话类,它会看起来像:

    def save() {
        int user_id = session['user_id']
        def user = Person.get(user_id)
        def number = new Telephone(params)
        number.person = user // important to create relation
        number.save() // pay attention here, that in previous example the Person was saved, but now the Telephone is
    }

此外,当使用staticbelongsTo=[Person:Person]时,您不需要在Telephone类中声明Person字段。无论如何都会创建该属性。

最后一个提示,在创建域类之后,尝试运行grails generate all Person命令(如果仍然使用grails generated all Telephone)。这将为您的域类"脚手架"默认控制器和视图,您可以将它们用作示例。

您的代码看起来有点过于复杂,我认为,您的目标应该更容易实现,请尝试查看Grails文档,该文档描述了一对多关系,您正在使用:http://grails.org/doc/latest/guide/GORM.html#oneToMany

相关内容

最新更新