Flavian
Flavian

Reputation: 65

GORM set null on foreign key in many to one relationship on delete

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

Answers (1)

James Kleeh
James Kleeh

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

Related Questions