为简化起见,假设我有三个表:
val postTable = TableQuery[Posts]
val postTagTable = TableQuery[PostTags]
val tagTable = TableQuery[Tags]
Run Code Online (Sandbox Code Playgroud)
一个帖子可以有多个标签,postTagTable只包含关系.
现在我可以像这样查询帖子和标签:
val query = for {
post <- postTable
postTag <- postTagTable if post.id === postTag.postId
tag <- tagTable if postTag.tagId === tag.id
} yield (post, tag)
val postTags = db.run(query.result).map {
case result: Seq[(Post,Tag)] =>
result.groupBy(_._1).map {
case (post, postTagSeq) => (post, postTagSeq.map(_._2))
}
}
Run Code Online (Sandbox Code Playgroud)
哪个会给我一个Future[Seq[(Post, Seq(Tag))]].
到现在为止还挺好.
但是,如果我想为帖子添加分页呢?由于一个人Post可以拥有Tags上述查询的多个,我不知道查询中有多少行take,以便得到,比方说,10 Posts.
有没有人知道在一个查询中使用特定数量的帖子获得相同结果的好方法?
我实际上甚至不确定如何在没有嵌套查询的情况下在本机SQL中处理此问题,因此如果有人在该方向上有建议,我也很乐意听到它.
谢谢!
编辑 …