Reputation: 65
My domain:
Company {
String name
}
Contact {
String name
Company compa
static constraints = {
compa (nullable: true)
}
}
I can't delete a Company if it has a foreign key constraint from a Contact. I want the delete to work and the compa attribute to be set to null on deleting a Company.
Is there a constraint that does this ? Is there a better way to do it than I am trying ?
Upvotes: 0
Views: 2901
Reputation: 12228
Give this a try, maybe there are other options. I haven't tested this code, just to give you an idea.
In Company.groovy:
def beforeDelete() {
Contact.withNewSession {
Contact.findAllByCompany(this).each {
it.company = null
it.save()
}
}
}
Upvotes: 3