Scala 流畅的一对多和分组
我试图用Slick 3.1.0对以下内容进行建模Scala 流畅的一对多和分组,scala,slick,Scala,Slick,我试图用Slick 3.1.0对以下内容进行建模 case class Review(txt: String, userId: Long, id: Long) case class User(name: String, id: Long) case class ReviewEvent(event: String, reviewId: Long) 我需要填充一个名为FullReview的类,如下所示 case class FullReview(r: Review, user: User, evt
case class Review(txt: String, userId: Long, id: Long)
case class User(name: String, id: Long)
case class ReviewEvent(event: String, reviewId: Long)
我需要填充一个名为FullReview
的类,如下所示
case class FullReview(r: Review, user: User, evts: Seq[ReviewEvent])
假设我对每个模型都有正确的表,我将尝试使用join和group by组合获取FullReview
,如下所示:
val withUser = for {
(r, u) <- RTable join UTable on (_.userId === _.id)
}
val withUAndEvts = (for {
((r, user), evts) <- withUser joinLeft ETable on {
case ((r, _), ev) => r.id === ev.reviewId
}
} yield (r, user, events)).groupBy(_._1._id)
val withUser=for{
(r,u)通过一些修补,我认为最好在客户端上进行聚合。这间接地意味着,如果表ETable
上的100行与RTable
上的一行匹配,则客户端上会有多行。然后,客户端必须实现自己对组a的聚合通过Review
调用ReviewEvent
就分页而言,您可以执行以下操作:
def withUser(page: Int, pageSize: Int) = for {
(r, u) <- RTable.drop(page * pageSize).take(pageSize) join UTable on (_.userId === _.id)
}
def withUser(page:Int,pageSize:Int)=用于{
(r,u)如果我理解正确,您可以使用以下示例:
val users = TableQuery[Users]
val reviews = TableQuery[Reviews]
val events = TableQuery[ReviewEvents]
override def findAllReviews(): Future[Seq[FullReview]] = {
val query = reviews
.join(users).on(_.userId === _.id)
.joinLeft(events).on(_._1.id === _.reviewId)
db.run(query.result).map { a =>
a.groupBy(_._1._1.id).map { case (_, tuples) =>
val ((review, user), _) = tuples.head
val reviewEvents = tuples.flatMap(_._2)
FullReview(review, user, reviewEvents)
}.toSeq
}
}
如果你想给这个请求添加分页,我已经回答了,这是一个完整的例子。错误是什么?@pamu本身没有错误。你如何在db.run
块中使用它?比如说,我想得到一个Seq[FullReview]
查询数据库以获得用户id的评论列表
?请参阅精彩的博客文章。@insan-e谢谢。这确实提供了一些提示,但它涉及到在客户端对内容进行分组。作为一种解决方法,这是可以的,但我相信这可以在MySQL中完成,并且在某个阶段应该得到Slick的支持。此外,这会导致各种问题在我们的例子中,Review
可以有数千个ReviewEvent
条目,如果能够让数据库处理分组,那就太好了。第一句话说:“Slick是一个函数关系映射”库。它不是像Hibernate那样的ORM,它是为您做的…:d感谢您的回答。这正是我一直在做的,也是我的答案所建议的。分组必须在客户端上完成。这种方法的问题是,您最终检索了1000行,用于包含1000个事件的审阅。这是我喜欢的为了避免。我想看看是否有人在这种情况下运行过性能指标。小提示:您可以使用.mapValues
而不是.map with case