我有以下情况:
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实例?我需要更改什么才能自动删除并删除错误?
答案 0 :(得分:2)
班级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
到Receipt
,负责删除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)。