Slick 2 aggregation - how to get a scalar result?

2019-08-11 17:29发布

问题:

I have a table with an Int column TIME in it:

def time = column[Int]("TIME")

The table is mapped to a custom type. I want to find a maximum time value, i.e. to perform a simple aggregation. The example in the documentation seems easy enough:

val q = coffees.map(_.price)
val q1 = q.min
val q2 = q.max

However, when I do this, the type of q1 and q2 is Column[Option[Int]]. I can perform a get or getOrElse on this to get a result of type Column[Int] (even this seems somewhat surprising to me - is get a member of Column, or is the value converted from Option[Int] to Int and then wrapped to Column again? Why?), but I am unable to use the scalar value, when I attempt to assign it to Int, I get an error message saying:

type mismatch;
 found   : scala.slick.lifted.Column[Int]
 required: Int

How can I get the scala value from the aggregated query?

回答1:

My guess is that you are not calling the invoker that's the reason why you get a Column object. Try this:

val q1 = q.min.run

Should return an Option[Int] and then you can get or getOrElse.