n92
n92

Reputation: 7592

How to delete an entry from joined table of many-to-many relationship in grails

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.

Upvotes: 1

Views: 3388

Answers (3)

MBozic
MBozic

Reputation: 1192

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)

Upvotes: 3

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()

Upvotes: 3

Nickmancol
Nickmancol

Reputation: 1044

You could implement the m:n collections avoiding the hasMany/belongsTo technique using the approach explained by Mr Burt Beckwith, this improves the performance and can help you to safely delete the 'attachment_mail_drafts' entity that you need.

Upvotes: 0

Related Questions