user3514920
user3514920

Reputation: 181

How to insert in Kotlin Exposed a record with the foreign key?

I cannot find in Kotlin Exposed documentation the way how to insert a record with the foreign key:

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

Upvotes: 4

Views: 3794

Answers (1)

Tapac
Tapac

Reputation: 2337

You should do that the same way as you insert any other value - provide proper 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
    }
}

Upvotes: 5

Related Questions