Groovy/Grails many-to-many delete relation -
i have 2 domain class many many relationship. when delete entity belongs other, have remove relation before in order avoid foreign key error. these relations connected via third class, third table in mysql.
class city { string namecity static hasmany = [visits:visit] /* first variant. removes 1 visit */ def beforedelete() { visit.withnewsession { def visitlist = visit.findbycity(this) visitlist.each { it.delete(flush: true) } } } } //_____________________________________________ class visit { // relation class city city person person } //_____________________________________________ class person { string nameperson static hasmany = [visits:visit] }
so when delete relation between 2 classes, removes 1 relation only. mean, if have 1 city , 1 person, , try delete city, app functions ok. if have more 1 person attached city, have: "cannot delete or update parent row: foreign key constraint fails". 1 relation deleted. if try delete city 1 more time, second person deleted. app behaves until last person deleted. so, beforedelete() method works great. problem don't understand how create collection of relations , remove them in cycle (loop). if make this:
class city { string namecity static hasmany = [visits:visit] /* second variant. type cast exception */ collection<visit> visitlist() { visit.findbycity(this) } def beforedelete() { visit.withnewsession { visitlist().each { it.delete(flush: true) } } } }
i have org.codehaus.groovy.runtime.typehandling.groovycastexception 'cannot cast object 'mypackage.visit : 1' class 'mypackage.visit' class 'java.util.collection'. thoughts , highly appreciated.
have tried following? in theory should work...
class city { string namecity static hasmany = [visits:visit] class visit { // relation class city city person person static belongsto = [city:city, person:person] } class person { string nameperson static hasmany = [visits:visit] }
and make normal delete. in way, if delete city or person, related visits deleted
Comments
Post a Comment