gpt4 book ai didi

grails - 用额外的列一对多

转载 作者:行者123 更新时间:2023-12-02 16:00:54 25 4
gpt4 key购买 nike

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

class Receipt_HealthService {

Receipt receipt
HealthService healthService
int quantity = 1

static constraints = {
}
}

在收据中,我有以下内容:
 @NotNull
static hasMany = [healthServices:Receipt_HealthService]

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

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

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

收据1已创建为:

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

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

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

    收据1:

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

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

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

  • 最佳答案

    我已使用以下代码解决了此问题。我希望有人能对此发表评论。

    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
    }

    关于grails - 用额外的列一对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30954545/

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