https://kotlinlang.org logo
#exposed
Title
# exposed
r

Richard Romanowski

03/14/2022, 3:40 PM
Copy code
object UserRatings: IntIdTable() {
    val value = long("value")
    val film = reference("film", StarWarsFilms)
    val user = reference("user", Users)
}
class UserRating(id: EntityID<Int>): IntEntity(id) {
    companion object : IntEntityClass<UserRating>(UserRatings)
    var value by UserRatings.value
    var film by StarWarsFilm referencedOn UserRatings.film // use referencedOn for normal references
    var user by User referencedOn UserRatings.user
}
If I have the ID of a film how can I create a new rating with the DAO api? Example:
Copy code
val filmId: UUID = getFilmId()
val rating = UserRating.new {
  // what goes here to set film?
}
c

Calvin

03/14/2022, 3:42 PM
does this work?
film = FilmEntity[filmId]
or maybe
film = StarWarsFilm[filmId]
r

Richard Romanowski

03/14/2022, 3:47 PM
No, I don't understand what this syntax is trying to do
c

Calvin

03/14/2022, 3:50 PM
You have the ID of the entity, so i'm trying to get you a filmentity object from the ID so you can set the reference when creating the UserRating
Does a get method exist on the StarWarsFilm class? StarWarsFilm.get(filmId)
Copy code
val rating = UserRating.new {
  film = StarWarsFilm.get(filmId)
}
h

hfhbd

03/14/2022, 3:51 PM
var filmID by UserRatings.film
Copy code
new {
    this.filmID = filmId
}
r

Richard Romanowski

03/14/2022, 5:14 PM
@Calvin I want to avoid another database call if I already have the ID, since the column is just and ID with a FK defined
@hfhbd What do I lose by removing
referencedOn
?
h

hfhbd

03/14/2022, 5:16 PM
You can have both.
ReferencedOn
reads the whole row from the referenced table
r

Richard Romanowski

03/14/2022, 5:16 PM
But if I have
referencedOn
I don't see how to set that field when I'm creating a new record when I have the id of the reference I want to set without making an extra call to the db
h

hfhbd

03/14/2022, 5:18 PM
Use both: If you already have the dao, use
new { this.film = filmDao }
If you already have the id, use
new { this.filmID = filmId }
.
r

Richard Romanowski

03/14/2022, 5:19 PM
I get an error that it's expecting the entity instead of just the UUID
h

hfhbd

03/14/2022, 5:20 PM
Add
var filmID by UserRatings.film
Copy code
class UserRating(id: EntityID<Int>): IntEntity(id) {
    companion object : IntEntityClass<UserRating>(UserRatings)
    var value by UserRatings.value
    var film by StarWarsFilm referencedOn UserRatings.film // use referencedOn for normal references
    var filmID by UserRatings.film
    var user by User referencedOn UserRatings.user
}
val filmId: UUID = getFilmId()
val rating = UserRating.new {
  filmID = filmId
}
r

Richard Romanowski

03/14/2022, 5:21 PM
ah, I can put both. cool. let me try that
Working. Thanks for the tip
3 Views