代码之家  ›  专栏  ›  技术社区  ›  FrancescoDS

删除父行中的grails外键错误

  •  0
  • FrancescoDS  · 技术社区  · 9 年前

    我有以下情况:

    class Receipt {
    
       BigDecimal totalAmount;
       Date releaseDate;
    
       @NotNull
       Integer vatPercentage;
    
       @NotNull
       Integer discount;
    
       Boolean isPayed;
       Boolean isInvoice;
       Boolean hasStampDuty;
    
       Integer documentNumber;
    
       @NotNull
       static belongsTo = [patient:Patient, doctor:Doctor]
    
       @NotNull
       static hasMany = [healthServices:Receipt_HealthService]
    
    
        static constraints = {
            healthServices(blank:  false)
            patient(blank: false)
            totalAmount(blank: false, )
            vatPercentage(blank: false, nullable: false)
    
        }
    
    
    }
    
    
    class HealthService {
    
       int vat;
       String description;
       BigDecimal price;
    
       static belongsTo = [healthServiceType:HealthServiceType, doctor:Doctor]
    
       static constraints = {
          healthServiceType(blank: false)
          vat(size: 11..11)
          description(maxSize: 255)
    
        }
    }  
    
    
    class Receipt_HealthService {
    
       Receipt receipt
       HealthService healthService
       int quantity = 1
    
       static constraints = {
       }
    }
    

    我已经手动创建了Receipt_HealthService域类,如文章所述 here . 一切正常,但当我尝试删除Receipt实例时,我看到以下错误:

    Cannot delete or update a parent row: a foreign key constraint fails
    (`my_localdb`.`receipt_health_service`, CONSTRAINT 
    `FK96DE98B9D3292D2C` FOREIGN KEY (`receipt_id`) REFERENCES `receipt`(`id`))
    

    为什么会发生这种情况?为什么Receipt_HealthService实例不会自动删除?我需要更改什么才能允许自动删除并删除错误?

    1 回复  |  直到 8 年前
        1
  •  2
  •   Deigote    9 年前

    班级 Receipt_HealthService 没有 belongsTo 因此 Receipt 的删除未级联。看见 http://grails.github.io/grails-doc/latest/guide/GORM.html#cascades .

    您可以更改 Receipt_HealthService(接收健康服务) 如下所示:

    class Receipt_HealthService {
       ...
       static belongsTo = [receipt: Receipt]
    }
    

    或者尝试明确定义级联行为(参见 http://grails.github.io/grails-doc/latest/guide/GORM.html#customCascadeBehaviour ).

    另一种可能性是添加 beforeDelete 收据 负责删除中的每个条目 healthServices 看见 http://grails.github.io/grails-doc/latest/guide/GORM.html#eventsAutoTimestamping

    对于最后一个选项,您可以检查类 User , UserRole Role 来自 Spring Security Plugin 例如。我在网上找不到示例项目,但您可以在示例项目中安装插件并运行 grails s2-quickstart 看看 User#beforeDelete 看起来像(参见 https://grails-plugins.github.io/grails-spring-security-core/ref/Scripts/s2-quickstart.html ).