【问题标题】:Assign foreign key value in grails在grails中分配外键值
【发布时间】:2014-05-12 17:41:18
【问题描述】:

我有一个名为 District 的域,我将只输入地区名称,它工作正常。我有另一个名为 Thana 的域,我需要将 District id 作为外键,因为一个区域下有这么多的 Thana。我想将thana名称和地区ID作为外键值保存在thana表中。这就是为什么我从组合 addThana 视图中获取区 ID。但是当我分配值时,它的给出错误。任何人都可以请帮我吗?以下是我的过程:

我的区域>>

    class District {
    String districtName

    static constraints = {
    }

    static mapping = {
        table('district')
        version(false)
    }
}

我的域名>>

    class Thana {

    String thanaName
    District district

    static constraints = {
    }

    static mapping = {
        table('thana')
        version(false)
        district column: 'district_id'
    }
}

我的保存方法>>

def saveThana(){
    println(params)
    Thana thana = new Thana()

    thana.district = params.districtId
    thana.thanaName = params.thanaName
   thana.save()
}

和错误信息>>

消息: 参数类型不匹配

【问题讨论】:

  • 使用这个:thana.district = District.get(params.districtId)
  • @JoshuaMoore 非常感谢。它工作正常。但是你为什么不把答案区放在!!!?

标签: grails grails-2.0 grails-domain-class


【解决方案1】:

那是因为 params.districtId 是 String 并且您将其分配给 District 类型的属性。

所以你必须先检索 District 的一个实例,你可以使用 id:

thana.district = District.get(params.districtId?.toLong())

【讨论】:

    【解决方案2】:

    原因是 Thana 类想要一个 District Object 而不是 District_id 来保存 District 作为与 Thana 表的前键关系。

    你应该做的更清楚。

    def saveThana(){
        println(params)
    
    try {
    
        Thana thana = new Thana()
        thana.district = District.findById(params?.districtId) //check nulls okay?
        thana.thanaName = params?.thanaName.toString()
        thana.save(failonSave:true)
    }
    catch(exception ex){
    println ("Save Error":ex.getMessage());
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多