繁体   English   中英

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

[英]How to save a Foreign key from a controller class in Grails?

是Groovy nd Grails的新手。我不知道如何将外键保存到子表中。 我有两个域类,分别称为Person和Telephone。我必须尝试保存,但不起作用。请帮助我。

人格

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
    }
}

电话业务

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
    }
}

登录人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
    }

同样,当使用静态belongsTo = [person:Person]时,您不需要在Telephone类中声明Person字段。 无论如何将创建该属性。

最后一个技巧是,在创建您的域类之后,尝试运行命令grails generate-all Person(如果仍然使用grails generate-all Telephone)。 这将“架设”域类的默认控制器和视图,您可以将其用作示例。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM