用额外的列一对多 [英] grails one to many with additional column

查看:95
本文介绍了用额外的列一对多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my Grails project I need to have a 1:N relationship between two domain classes. So, I've created the following domain class:

class Receipt_HealthService {

   Receipt receipt
   HealthService healthService
   int quantity = 1

   static constraints = {
     }
}

在收据中,我有以下内容:

and in Receipt I have the following:

 @NotNull
static hasMany = [healthServices:Receipt_HealthService]

因此,将创建一个新表,该表同时具有域类的ID和quantity字段.

So a new table is created that has got the id of both domain class and the quantity field.

当我调用save()方法时,一切工作正常,但是当我调用update()时,则无法正常工作.

When I call the save() method everything works well, but when I call the update() something does not work.

如果用户修改了收据,删除了先前保存的HealthService之一,而又修改了其他收据,则较旧的HealthServices将与新的HealthService一起保存.例如:

If user modifies the Receipt, removing one of the HealthService previously saved, and modifying the others, older HealthServices remain saved with the new ones. For example:

使用1创建的收据:

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

收据1的修改

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

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

After the update() I have the following:

接收1:

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

我认为此行为是由于添加了新的域类而引起的.也许我可以在update()中手动添加正确保存的HealthService吗?

I suppose that this behaviour is because of adding the new domain class. Do I maybe add manually the correct saving of HealthService in update()?

以前有关save()的问题已解决,无法更改代码.我使用的方法在我的代码中不再有用.该方法使用的ReceinceInstance在方法调用时未填充数据,因此在save()中出现了异常.

the previous problem about save() is solved changing the code. I was using a method that is no more useful in my code. That method uses receiptInstance that, at the moment of method calling, is not filled with data and so I had the exception in save().

推荐答案

我已使用以下代码解决了此问题.我希望有人给我评论.

I've solved this issue with the following code. I hope that someone gives me a comment about it.

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
    }

这篇关于用额外的列一对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆