【问题标题】:grails one to many with additional column带有附加列的一对多的 g​​rails
【发布时间】:2015-06-20 13:31:06
【问题描述】:

在我的 Grails 项目中,我需要在两个域类之间建立 1:N 关系。因此,我创建了以下域类:

class Receipt_HealthService {

   Receipt receipt
   HealthService healthService
   int quantity = 1

   static constraints = {
     }
}

在收据中我有以下内容:

 @NotNull
static hasMany = [healthServices:Receipt_HealthService]

因此,创建了一个新表,其中包含域类的 id 和 quantity 字段。

当我调用 save() 方法时,一切正常,但是当我调用 update() 时,有些东西不起作用。

如果用户修改了 Receipt,删除了之前保存的 HealthService 之一,并修改了其他的,旧的 HealthService 仍然与新的 HealthService 一起保存。例如:

使用以下创建的收据 1:

  • HealthService 1,数量 = 2
  • 数量 = 3 的 HealthService 2

收据 1 的修改:

  • HealthService 1 已删除
  • HealthService 2 修改为数量 = 2
  • 数量 = 1 的 HealthService 3

在 update() 之后,我有以下内容:

收据 1:

  • HealthService 1,数量 = 2
  • 数量 = 2 的 HealthService 2
  • 数量 = 1 的 HealthService 3

我想这种行为是因为添加了新的域类。我是否可以在 update() 中手动添加 HealthService 的正确保存?

编辑: 之前关于 save() 的问题是通过更改代码解决的。我正在使用一种在我的代码中不再有用的方法。该方法使用receiptInstance,在方法调用的那一刻,它没有填充数据,所以我在save()中遇到了异常。

【问题讨论】:

  • 你的参数包含什么?另外,为什么要创建 Receipt_HealthService 类,为什么要在 hasMany 上放置 @NotNull ?这不是您在 grails 中创建一对多关系的方式。请参阅grails.github.io/grails-doc/latest/guide/GORM.html#oneToMany 并且非空约束应该进入约束闭包。见grails.github.io/grails-doc/latest/guide/…
  • 我创建了 Receipt_HealthService 类,因为我需要将额外的列数量添加到关系中,我认为这是唯一的方法。关于@NotNull 你是对的,我会改变它,但问题仍然存在
  • @vahid 给出的样本有什么用?
  • 对不起,我以为它有行号 - 看照片有很多,然后看第 24 行 - 如上面 philippe 的 cmets 所指出的,可空:true 设置为约束。这是菲利普指出的关于你的帖子的一般观点。实际问题将在他问题的第一部分在您的参数中 - 只需在保存之前执行 println params 即可查看正在尝试保存的内容。 if (!b.save()) { b.errors.each { println it } } grails.github.io/grails-doc/latest/ref/Domain%20Classes/… 找出它没有保存的内容

标签: grails relationship one-to-many


【解决方案1】:

我已经用下面的代码解决了这个问题。我希望有人给我一个评论。

receiptInstance.healthServices.collect().each {
        //I've tried to use receiptInstance.healthServices.clear()
        //but Set remains with all items 

        //delete item from Set
        receiptInstance.healthServices.remove(it) 
        //delete item from DB
        it.delete()
    }

         //save with flush to commit the delete
    if (!receiptInstance.save(flush: true)) {
        render(view: "edit", model: [receiptInstance: receiptInstance])
        return
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多