문제

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
도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top