【问题标题】:How to insert in Kotlin Exposed a record with the foreign key?如何在 Kotlin 中插入带有外键的记录?
【发布时间】:2019-06-03 15:43:20
【问题描述】:

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

【问题讨论】:

    标签: kotlin kotlin-exposed


    【解决方案1】:

    您应该以与插入任何其他值相同的方式执行此操作 - 提供正确的 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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多