如何在Kotlin中插入带有外键的公开记录?

时间:2019-06-03 15:43:20

标签: kotlin kotlin-exposed

我在Kotlin Exposed文档中找不到如何使用外键插入记录的方法:

object DocumentTable : IntIdTable() {
    val description = varchar("desc", 200)
}

object TransactionTable : IntIdTable() {
    val amount = long("amount")
    val documentId = reference("documentId", DocumentTable.id)
}

fun createTrans(amount: Long, document: Document) {
    transaction {
        TransactionTable.insert {
           it[this.amount] = amount
           it[this.documentId] =  ?????????????
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您应该执行与插入其他任何值相同的方法-提供正确的documentId

transaction {
    val docId = DocumentTable.select { /*your condition here */ }.single()[DocumentTable.id] 
    // or if you want to construct your id from scratch (be sure that you have such record in a database or it will fail with exception)
    val docId = EntityID(123, DocumentTable)

    TransactionTable.insert {
       it[this.amount] = amount
       it[this.documentId] = docId
    }
}