scalaslickslick-2.0

Using multiple projection in slick for the same table


I have a user table for which I will like to have multiple projections. For example, Can I have something like


class Users(tag: Tag) extends Table [User] (tag, "user") {
def * = (id.?, emailId, firstName, lastName, gender) <> (User.tupled, User.unapply)
def allDetails = (id.?, emailId, firstName, lastName, gender, createdTime, modifiedTime)
...
}
I searched on Google but could not find anything. Can somebody tell me how can I use allDetails?

I will like to do


object Users  {
  val users = TableQuery[Users]
  def getAllDetails = ??? // How can I use allDetails here
  }


Solution

  • Do like this:

       class UserTable(tag: Tag) extends Table[UserInfo](tag, "user") {
        def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
        def emailId = column[String]("email_id", O.NotNull)
        def firstName = column[String]("firstname")
        def lastName = column[String]("lastname")
        def gender = column[String]("gender")
        def createdTime = column[Option[Timestamp]]("created_time")
        def modifiedTime = column[Option[Timestamp]]("modified_time")
        def userInfo = (emailId, firstName, lastName, gender, createdTime, modifiedTime, id.?) <> (User.tupled, User.unapply)
    
         def * = (emailId, firstName, lastName, gender, id.?) <> (UserInfo.tupled, UserInfo.unapply)
    

    }

     case class User(emailId: String,
       firstName: String, lastName: String, gender: String, 
       createdTime: Option[Timestamp],    
       modifiedTime: Option[Timestamp], id: Option[Int] = None)
    
     case class UserInfo(emailId: String, firstName: String, lastName: String, 
          gender: String, id: Option[Int] = None)
    

    for extra projection:

      val userTable = TableQuery[UserTable]
    
     def insert(userInfo: UserInfo) (implicit session: Session): Int = {
       //return auto incremeted id
      userTable returning (userTable.map(_.id)) += userInfo
    
      }
    
     def update(userInfo: UserInfo)(implicit session: Session) = {
       userTable.filter(_.id === userInfo.id).update(userInfo)
     }
     def getUserInfo()(implicit session: Session): List[UserInfo] = {
      userTable.list
    
      }