【问题标题】:How to delete an entry from joined table of many-to-many relationship in grails如何从grails中多对多关系的连接表中删除条目
【发布时间】:2012-09-18 09:27:50
【问题描述】:

我有两个域对象

Class Attachment{
    static hasMany = [mailDrafts: MailDraft];
}

Class MailDraft{
  static hasMany = [attachments: Attachment]
   static belongsTo = Attachment
} 

它已经创建了三个表

1)attachment
2)mail_draft 
3)attachment_mail_drafts

attachment_mail_drafts: id, mail_draft_id

现在,我想写一个 HQL 查询to delete an entry from the table 'attachment_mail_drafts' where 'attachment_id' is 4,那么查询是什么。

【问题讨论】:

    标签: grails many-to-many hql grails-orm grails-2.0


    【解决方案1】:

    你不能用 HQL 做到这一点,你可以阅读更多为什么here。 相反,您将执行以下操作:

    def a = Attachment.get(4)
    a.mailDrafts.clear()
    a.save()
    

    【讨论】:

      【解决方案2】:

      似乎在 HQL 中您只能删除对象,无法删除关联。您可以使用原始 SQL 或使用 GORM 方法 removeFrom:

      def attachment = Attachment.get(1)
      def mailDraft = attachment.mailDrafts.find { it.id = 4 }
      attachment.removeFromMailDrafts(mailDraft).save(flush: true)
      

      【讨论】:

        【解决方案3】:

        您可以使用 Burt Beckwith 先生的方法 explained 来实现 m:n 集合,避免使用 hasMany/belongsTo 技术,这可以提高性能并可以帮助您安全地删除您 need 的“attachment_mail_drafts”实体。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-05-10
          • 1970-01-01
          • 2019-12-20
          • 2016-04-12
          • 1970-01-01
          • 2015-02-21
          • 2017-07-13
          • 2012-02-17
          相关资源
          最近更新 更多