Search code examples
kotlinktorkotlin-exposed

Kotlin ktor exposed DSL insert with reference


I am developing a Kotlin with ktor application and I am using exposed as ORM. I have a table with a reference to another table. The relationship is many to one. ex:

object Users : IdTable<String>() {
   override val id: Column<EntityID<String>> = varchar("user_id", 64).entityId().primaryKey()
   val email = varchar("email", 128).uniqueIndex()
   val firstName = varchar("first_name", 64)
   val lastName = varchar("last_name", 64)
}

& User Attendance table as -

object UserAttendances : IntIdTable() {
   val userId = reference("user_id", Users).index()
   val checkInTime = date("check_in")
   val checkOutTime = date("check_out")
}

Now when I am trying to insert into the attendance table, i am not sure how to map the insert to users. I tried the following -

StaffAttendances.insert {
    it[date] = DateTime.now()
    it[checkInTime] = DateTime.now()
    it[userId] = userId
}

This gives a compilation error that the required type is EntityId<String> but found String. Any help on how i can insert into a reference. This could possibly be because I have String as ID column with UUIDs


Solution

  • The userId must take an EntityId<String>. So you should pass your userId as it[userId] = EntityId(userId, Users).

    To avoid this, I use plain Table instead of IntIdTable and manually create my primary key. This way I can pass directly the value without wrapping it in an EntityId<>.