Hi, I'm looking to see if it's possible to update ...
# exposed
r
Hi, I'm looking to see if it's possible to update a record and the child records. Is this possible in a single DAO update? Here is an example of a basic pattern I'd like to implement. Fetch a record and the relationships. Update stuff. Then save the changes (Modification to parent or child records, add/remove of child records)
Copy code
import org.jetbrains.exposed.dao.UUIDEntity
import org.jetbrains.exposed.dao.UUIDEntityClass
import org.jetbrains.exposed.dao.id.EntityID
import org.jetbrains.exposed.dao.id.UUIDTable
import org.jetbrains.exposed.dao.load
import java.util.UUID

data class Toy(
    val id: UUID = UUID.randomUUID(),
    val type: String,
)

data class User(
    val id: UUID,
    val name: String,
    val toys: List<Toy>
)

object Users : UUIDTable( "users") {
    val name = text("name")
}

class UserRecord(id: EntityID<UUID>) : UUIDEntity(id) {
    companion object : UUIDEntityClass<UserRecord>(Users)

    var name by Users.name
    val toys by ToyRecord referrersOn Toys.userId

    fun toDomain() = User(
        id.value,
        name,
        toys.map { it.toDomain() },
    )
}

object Toys : UUIDTable( "toys") {
    val userId = reference("user_id", Users)
    val type = text("type")
}

class ToyRecord(id: EntityID<UUID>) : UUIDEntity(id) {
    companion object : UUIDEntityClass<ToyRecord>(Toys)

    var type by Toys.type

    fun toDomain() = Toy(
        id.value,
        type,
    )
}

// 1. Fetch record with references
val user = UserRecord.findById(UUID.randomUUID())!!.load(UserRecord::toys).toDomain()

// 2. Do complex business logic that results in mutation of references
val updatedUser = user.copy(
    name = "New name",
    toys = user.toys + Toy(type = "puzzle")
)

// 3. Update database
// ???
UserRecord.findById(updatedUser.id)!!.apply {
    name = updatedUser.name
    toys = updatedUser.toys
    // Doesn't work for many reasons: (1) is val, (2) mismatched types
}