1

我有一个非常简单的关系,通常级联删除应该起作用。我的关系是这样的:

enum StatusName {
    PENDING, SENDING, SENT
}

abstract class Notification {
    StatusName status = StatusName.PENDING
    Date dateCreated
    Date scheduledDate
    String text = ""
    User recipient
    boolean hasBeenSeen = false

    static belongsTo = [
        selectedChannel: SelectedChannel
    ]

    static constraints = {
        status blank: false, 
            inList:[StatusName.PENDING, StatusName.SENDING, StatusName.SENT]
        scheduledDate nullable: true
        text size: 0..1000
        recipient nullable: true 
    }

    def beforeInsert() {
        if(!recipient) { 
            recipient = selectedChannel?.user
        }
    }

}

这里是其他类:

包 de.carmeq.carmob

class SelectedChannel {

    static hasMany = [
        notifications: Notification
    ]

    static belongsTo = [
        channel: Channel,
        user: User,
        notificationType: NotificationType
    ]

    static constraints = {
        channel blank: false,
        user blank: false,
        notificationType blank: false, unique: ['channel', 'user']
    }
}

我想删除给定用户的所有 selectedChannels,所以我执行以下操作:

Collection<SelectedChannel> selectedChannels = SelectedChannel.findAllByUser(greedyUser)
selectedChannels*.delete()

但这会导致以下错误:

Referential integrity constraint violation: "FK237A88EBC25A325D: PUBLIC.NOTIFICATION FOREIGN KEY(SELECTED_CHANNEL_ID) REFERENCES PUBLIC.SELECTED_CHANNEL(ID)"; SQL statement:

从 id=? 的 selected_channel 中删除 和版本=?[23503-164]

即使我像这样删除所有通知:

Collection<Notification> notifications = Notification.findAllByRecipient(greedyUser)
notifications*.delete()

我犯了同样的错误...

问候

4

1 回答 1

1

将此映射闭包添加到SelectedChannel域:

static mapping = {
    notifications cascade: 'all-delete-orphan'
}

并像这样删除 selectedChannels:

Collection<SelectedChannel> selectedChannels = SelectedChannel.findAllByUser(greedyUser)
selectedChannels.each{sc->
    sc.notifications.each{nt->
        sc.removeFromNotifications(nt)
    }
    sc.delete()
}

如果在or Domain中也引用了selectedChannels ,请先使用removeFrom方法清除引用。UserNotificationType

于 2013-03-13T03:44:05.673 回答