3

我在 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] =  ?????????????
        }
    }
}
4

1 回答 1

3

您应该以与插入任何其他值相同的方式执行此操作 - 提供正确的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
    }
}
于 2019-06-04T09:49:12.173 回答