如何在 Kotlin Exposed 的一对多关系中设置级联类型?

How to set cascade type in a One-To-Many relationship in Kotlin Exposed?

我有两个处于一对多关系中的实体。 "One" 实体拥有 "Many" 的生命周期。如果 "One" 实体被删除,我希望属于 "One" 的所有 "Many" 实体被自动删除。

我假设有一种方法可以像在 Hibernate 中那样将引用设置为 "CascadeType.DELETE",因此我不必在删除 "One" 之前删除所有 "Many"。

object Apis : IntIdTable() {
    val name = varchar("name", 20)
    val url = varchar("url", 255)
    val method = enumerationByName("method", 20, HttpMethod::class)
    val requestBody = varchar("request_body", 65535)
    val responseDsl = varchar("response_dsl", 65535)
    val responseType = enumerationByName("response_type", 20, ResponseType::class)
    val enabled = bool("enabled")
}

class Api(id: EntityID<Int>) : IntEntity(id){
    companion object : IntEntityClass<Api>(Apis)

    var name by Apis.name
    var url by Apis.url
    var method by Apis.method
    var requestBody by Apis.requestBody
    var responseDsl by Apis.responseDsl
    var responseType by Apis.responseType
    var enabled by Apis.enabled
    val headers by ApiHeader referrersOn ApiHeaders.id
}

object ApiHeaders : IdTable<Int>() {
    override val id = reference("api_id", Apis).primaryKey()
    val key = varchar("key", 255)
    val value = varchar("value", 255)
}

class ApiHeader(id: EntityID<Int>) : Entity<Int>(id) {
    companion object : EntityClass<Int, ApiHeader>(ApiHeaders)

    var api by Api referencedOn ApiHeaders.id
    var key by ApiHeaders.key
    var value by ApiHeaders.value
}

fun main() {
    transaction {
        addLogger(StdOutSqlLogger)
        val api = Api.findById(1)
        // if headers are not deleted, api can't be deleted directly
        api?.headers?.forEach { it.delete() }
        api?.delete()
        commit()
    }
}

我需要一种方法来轻松设置所需的级联关系类型。

reference()optReference() 函数有可选参数:onUpdate 和 onDelete。

在你的情况下你必须写:

object ApiHeaders : IdTable<Int>() {
    override val id = reference("api_id", Apis, onDelete = ReferenceOption.CASCADE).primaryKey()
    val key = varchar("key", 255)
    val value = varchar("value", 255)
}