我有一个名为Category的实体,它与自身有关系。有两种类别,父类别和子类别。子类别在idParent属性中具有来自父类别的id。
我用这种方式定义了Schema
class CategoriesTable(tag: Tag) extends Table[Category](tag, "CATEGORIES") {
def id = column[String]("id", O.PrimaryKey)
def name = column[String]("name")
def idParent = column[Option[String]]("idParent")
def * = (id, name, idParent) <> (Category.tupled, Category.unapply)
def categoryFK = foreignKey("category_fk", idParent, categories)(_.id.?)
def subcategories = TableQuery[CategoriesTable].filter(_.id === idParent)
}
我有这些数据:
id name idParent
------------------------------
parent Parent
child1 Child1 parent
child2 Child2 parent
现在我想将结果放在按父类别分组的地图中,如
Map( (parent,Parent,None) -> Seq[(child1,Child1,parent),(child2,Child2,parent] )
为此我尝试了以下查询:
def findChildrenWithParents() = {
db.run((for {
c <- categories
s <- c.subcategories
} yield (c,s)).sortBy(_._1.name).result)
}
如果此时我执行查询:
categoryDao.findChildrenWithParents().map {
case categoryTuples => categoryTuples.map(println _)
}
我明白了:
(Category(child1,Child1,Some(parent)),Category(parent,Parent,None))
(Category(child2,Child2,Some(parent)),Category(parent,Parent,None))
这里有两个事实让我感到不安:
订单被颠倒了,我希望父母首先出现如下:
(类别(父,母,无),类别(child1,Child1,有些(父))) (类别(父,母,无),类别(的child2,CHILD2,有些(父)))
现在我会尝试将它们分组。因为我在Slick中遇到嵌套查询问题。我按照这样的结果执行一组:
categoryDao.findChildrenWithParents().map {
case categoryTuples => categoryTuples.groupBy(_._2).map(println _)
}
但结果确实很糟糕:
(Category(parent,Parent,None),Vector((Category(child1,Child1,Some(parent)),Category(parent,Parent,None),(Category(child2,Child2,Some(parent)),Category(parent,Parent,None))))
我原以为:
(Category(parent,Parent,None),Vector(Category(child1,Child1,Some(parent)),Category(child2,Child2,Some(parent))))
你可以帮我解决倒置的结果和小组吗?
提前致谢。
答案 0 :(得分:1)
好的,我自己设法解决了这个问题。如果有人想从中学习,答案就在这里:
def findChildrenWithParents() = {
val result = db.run((for {
c <- categories
s <- c.subcategories
} yield (c,s)).sortBy(_._1.name).result)
result map {
case categoryTuples => categoryTuples.groupBy(_._1).map{
case (k,v) => (k,v.map(_._2))
}
}
}
解决方案并不完美。我想已经在Slick中创建该组,但这会检索我想要的内容。