Convert scala.slick.lifted.Query to case class

I have a smooth "UserSchema" table as follows:

class UserSchema(tag: Tag) extends Table[User](tag, "users") {

  def name = column[String]("name", O.NotNull)
  def password = column[String]("password", O.NotNull)
  def graduatingYear = column[Int]("graduating_year", O.NotNull)
  def id = column[Int]("id", O.NotNull, O.PrimaryKey, O.AutoInc)

  def * = (name, password, graduatingYear, id.?) <> (User.tupled, User.unapply)

}

My User class is as follows:

case class User(name: String, password: String, graduatingYear: Int, id: Option[Int] = None)

I have TableQuery[UserSchema]in the object usersand the database in the object db.

How can I convert the following to a User object?

db withSession { implicit session =>
  users.filter(_.id === 1)
}

At the moment I have

db withSession { implicit session =>
    val list = users.filter(_.id === id).list
    list(0)
}

which works but seems ugly to me. Is there a better way to do this?

Thanks for the help.

+1
source share
2 answers

The method list()returns List[User], but if you are only interested in the first record, use firstOption:

db withSession { implicit session =>
  val users = TableQuery[UserSchema]
  val someUser: Option[User] = users.filter(_.id === id).firstOption
}

Some(User), -, else None, , , , list(0) .

+1

Slick, :

db withSession { implicit session =>
  val userlist = users.filter(_.id === id).list
    .map(user => User(user._1, user._2, user._3, Some(user._4)))
}

userlist - User.

+1

Source: https://habr.com/ru/post/1568698/


All Articles