Reputation: 3024
Is it possible to use a foreign key field in a Slick where
or filter
statement?
Something like (where the user
field is a foreign key to a Table for which User
is its mapped projection) (this does not compile):
def findByUser(user: User)(implicit s: Session): Option[Token] =
tokens.where(_.user === user).firstOption
Or should we use the foreign key explicitely?
def findByUser(user: User)(implicit s: Session): Option[Token] =
tokens.where(_.userId === user.id).firstOption
Upvotes: 1
Views: 565
Reputation: 11270
Yes, ids are good.
def findByUserId(userId: Long)(implicit s: Session): Option[Token] =
tokens.filter(_.userId === userId).firstOption
findByUserId( user.id )
This allows the method to be used, even when the only thing you have is an id. Slick deliberately exposes the relational model (with a functional touch) and does not hide it, among other reasons because using id's instead of object references allows to refer to rows that are not loaded into memory merely by their id.
Or even better and simpler, because built into Slick:
val findByUserId = tokens.findBy(_.userId) // pre-compiles SQL for better performance
findByUserId(user.id).firstOption
Upvotes: 2