Search code examples
scalaslick

Is it common to create a new case class for join tables?


I have 2 tables like:

users
id
name

lists
-id
-name

user_lists
id
list_id
user_id

So I currently have a query that returns:

def getUsersByList(int listId): Future[Seq[UserList]] = {
  db.run( userLists.filter(f => f.listId === listId) )
}

Now I need to join with the User table in order to get the User fields.

What options do I have in what I return? I guess I have to create a new case class and map to the fields somehow?


Solution

  • I think that your question (though maybe I am wrong) doesn't actually refer only to case class by rather to case class (aka unpacked type) and table mapping (aka mixed type). Also it is important to understand that Slick won't help you in any way with one-to-many / many-to-many relationships (it's not an ORM). Here a little bit more: https://stackoverflow.com/a/42218139/2239369

    Long story short - your join table is table as any other. The general straightforward answer is: yes. Just create one more case class and table definition.

    You for sure need your join table definition (in short - this class that inherits from Slicks Table type - mixed type). Otherwise you wouldn't be able to generate appropriate query. You could probably go away from creating case class - but I am not sure if it is worth doing it - after all it's one additional line, right? ( case class UserList(id: Id, listId: Id, userId: Id) - or something close to this).

    It's perhaps worth to mention that you can also go away from all of above by creating a view on DB level.