How to handle unassigned IDs with anorm?
-
17-06-2021 - |
Question
Anorm has the special type anorm.Pk
for typed primary keys (and its subclass anorm.NotAssigned
). This allows to assign a NotAssigned
value if the database is responsible for generating the relevant key.
Is there an equivalent concept for foreign keys? I'm using type Long
at the moment. However, if the foreign key is not yet known, I will have to assign a null
value or replace the type by an Option[Long]
. This feels like it's not the way it's meant to be done, though.
Solution
Anorm doesn't offer functionality around relations.
Take your FK out of your model, but accept FKs as arguments to your CRUD, e.g. for creating a "Contrived" that belongs to a user:
def create(c: Contrived, userId: Long)
DB.withConnection { implicit connection =>
val id = SQL("""
insert into c
(first, second, login_id)
values
({first}, {second}, {login_id})
""").on(
'first -> c.first,
'second -> c.second,
'login_id -> userId
...etc
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow