gpt4 book ai didi

grails - Grails不会保存域的字段

转载 作者:行者123 更新时间:2023-12-02 15:44:51 25 4
gpt4 key购买 nike

我有两个 Realm 类(class)

class Country {
... // some fields, including other domains
}

class City {
... // some fields, including other domains
Country itsCountry
}

我的服务方法之一是在这里:
City createCity(String name, Country country) {
// country is existing and loaded in the controller's layer and passed here
City city = new City()
city.itsCountry = country // it is not persisted
city.save('flush':true)
}

问题在于,数据库中的城市为空国家。
当然,我简化了示例,实际上是更加复杂。 (不幸的是,一些重要的细节可能会丢失,希望您遇到这个问题,并分享原因)

我所做的没有成功的事情:
  • 和Country一起玩,在服务方法中通过id获取它,保存并刷新它,然后保存City对象
  • 使itsCountry字段不可为空。因此,我从数据库中得到一个异常(exception),即该字段不能为null。

  • 我觉得这一定是一件小事。可能是什么原因呢?

    最佳答案

    在Grails中,我们已经可以在params中获取国家/地区ID。
    例如params?.countryId。

    如果它是国家表的新记录,则首先为国家创建新对象并在城市对象中分配。

    例如,

    Country country = new Country()//for new record
    country.name=params?.countryName
    City city=new City()
    city.itsCountry = country
    city.save('flush':true)

    如果表中已经有国家/地区记录,则使用get方法获取对象并将其分配给城市。

    例如,
    Country country=Country.get(Long.valueOf(params?.countryId))
    city.itsCountry = country
    city.save('flush':true)

    希望对您有帮助。如有疑问,请ping我。

    关于grails - Grails不会保存域的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50376972/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com