尝试获取2周前的所有记录 [英] Trying to get all records from 2 weeks ago
问题描述
我正在尝试从2周前创建的表中获取所有记录.
I'm trying to get all records from a table that were created 2 weeks ago.
我的方法如下:
def getRecent(from: Instant): Future[Seq[User]] = {
db.run(
users.filter(f => f.status != 0 && f.createdAt > from ).sortBy(_.id.desc).result
)
}
我已经隐含了一个我认为可以使用的隐式功能,但我想它仅适用于读取行:
I have an implicit already that I thought would work but I guess it is only for reading rows:
class UsersTable(tag: Tag) extends Table[User](tag, "users") {
implicit val dateColumnType = MappedColumnType.base[Instant, Timestamp](
i => Timestamp.from(i),
ts => {
ts.toInstant
}
)
def id = column[Int]("id", O.PrimaryKey)
....
错误是:
value > is not a member of slick.lifted.Rep[java.time.Instant]
推荐答案
实际上,您已经快到了.它用于读取和写入.但事情是这样的:它必须在范围内(甚至用于过滤).
Actually you are nearly there. It is used for both read and writes. But here is the thing: it needs to be in scope (even for your filtering).
普通滑动解决方案
只需将您的转换放入这样的伴随对象中即可:
Just put your conversion into companion object like this:
object UserTable {
implicit val dateColumnType = MappedColumnType.base[Instant, Timestamp](
i => Timestamp.from(i),
ts => {
ts.toInstant
}
)
}
然后执行以下操作:
def getRecent(from: Instant): Future[Seq[User]] = {
// I added this import here
import UserTable.dateColumnType
db.run(
users.filter(f => f.status != 0 && f.createdAt > from ).sortBy(_.id.desc).result
)
}
Play-Slick解决方案
以上答案并不完全适合问题中未明确陈述的play-slick
部分(尽管问题已标记为playframework
).如果您使用的是play-slick
,那么您的方法将是这样的:
Above answer doesn't really fit play-slick
part which is not explicitly stated in the question (though question is tagged with playframework
tag). If you are using play-slick
than your approach would be something like this:
将您的对话放入trait
(trait DbImplicits
),该对话需要与HasDatabaseConfigProvider
混合在一起或扩展.
Put your conversation into trait
(trait DbImplicits
) that require to be mixed-in together with or extends HasDatabaseConfigProvider
.
trait DbImplicits { self: HasDatabaseConfigProvider[JdbcProfile] =>
import self.driver._
implicit val dateColumnType = MappedColumnType.base[Instant, Timestamp](
i => Timestamp.from(i),
ts => {
ts.toInstant
}
)
}
以后像这样使用它:
class MyClassUsingImplicits @Inject()(
protected val dbConfigProvider: DatabaseConfigProvider
) extends HasDatabaseConfigProvider[JdbcProfile]
with DbImplicits {
import driver._
// your further code comes here
}
顺便说一句,我刚刚注意到此片段中的另一个错误:
BTW I just noticed another mistake in this fragment:
f.status != 0
您应该使用Slick运算符:
You should be using Slick operator:
f.status =!= 0
这篇关于尝试获取2周前的所有记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!