爲了簡化假設我有三個表:在Slick 3.0中結合分頁和非查詢分組的好方法是什麼?
val postTable = TableQuery[Posts]
val postTagTable = TableQuery[PostTags]
val tagTable = TableQuery[Tags]
一個崗位可以有多個標籤和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))
}
}
這會給我Future[Seq[(Post, Seq(Tag))]]
。
到目前爲止這麼好。
但是如果我想爲帖子添加分頁呢? 因爲一個Post
可以有多個Tags
與上面的查詢,我不知道從查詢到take
有多少行,爲了得到,比方說,10 Posts
。
有誰知道在單個查詢中獲得與特定數量的帖子相同結果的好方法嗎?
我其實不確定我會如何在沒有嵌套查詢的情況下在本機SQL中處理這個問題,所以如果有人有這個方向的建議,我也很樂意聽到它。
謝謝!
編輯
只要你知道,我目前在做什麼類型的查詢:
val pageQuery = postTable drop(page * pageSize) take(pageSize)
val query = for {
pagePost <- pageQuery
post <- postTable if pagePost.id === post.id
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))
}
}
但是,這顯然導致嵌套查詢。這是我想避免的。
EDIT 2
另2查詢解決方案,這將是可能的:
val pageQuery = postTable drop(page * pageSize) map(_.id) take(pageSize)
db.run(pageQuery.result) flatMap {
case ids: Seq[Int] =>
val query = for {
post <- postTable if post.id inSetBind ids
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))
}
}
}
但是這將需要兩趟數據庫,並使用in
運營商,所以它可能不是那麼好作爲連接查詢。
有什麼建議嗎?
在這種情況下,slick的'groupBy'幫助不?如果你在查詢中用Post來做'groupBy',然後'take'? – Ixx
如果我在查詢上進行groupBy操作,我需要使用map來聚合我沒有分組的所有內容。因此,如果我將帖子分組(在查詢中),我無法獲得標籤爲列表,但只有例如數它們。 – thwiegan