How to delete an entry from joined table of many-to-many relationship in grails
-
02-07-2021 - |
Question
I have two domain objects
Class Attachment{
static hasMany = [mailDrafts: MailDraft];
}
Class MailDraft{
static hasMany = [attachments: Attachment]
static belongsTo = Attachment
}
It has created the three tables
1)attachment
2)mail_draft
3)attachment_mail_drafts
attachment_mail_drafts: id, mail_draft_id
Now, I wnat to write a a HQL query to delete an entry from the table 'attachment_mail_drafts' where 'attachment_id' is 4
, So what is the query.
Solution
You can't do this with HQL, you can read more why here. Instead you would do the following:
def a = Attachment.get(4)
a.mailDrafts.clear()
a.save()
OTHER TIPS
It seems that in HQL you can only remove objects, removing associations is not possible. You could use raw SQL or use GORM method removeFrom:
def attachment = Attachment.get(1)
def mailDraft = attachment.mailDrafts.find { it.id = 4 }
attachment.removeFromMailDrafts(mailDraft).save(flush: true)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow