具有一对多关系的精巧查询

时间:2018-10-25 14:27:13

标签: scala slick

我使用的是光滑的3.2.3版本,并且尝试构建一个查询,该查询返回具有一对多关系的两个实体的Seq[Entity1, Seq[Entity2]](对于每个Entity1都关联了多个Entity2)。

所以我有两个实体

case class Entity1(name: String, id: Option[Long] = None)
case class Entity2(entity1Id: Long, name: String, id: Option[Long] = None

具有表定义(由slick codegen任务生成)

class entity1Table(_tableTag: Tag) extends profile.api.Table[Entity1](_tableTag, "ENTITY_1") {
   ...
}
lazy val groupTable = new TableQuery(tag => new groupTable(tag))

class entity2Table(_tableTag: Tag) extends profile.api.Table[Entity2](_tableTag, "ENTITY_2") {
   ...
}
lazy val entity2Table = new TableQuery(tag => new entity2Table(tag))

阅读this article我已经创建了这样的查询

val q = (for {
  e1 <- entity1Table
  e2 <- entity2Table if e2.entity1Id === e1.id
} yield (e1, e2)).groupBy(_._1) map {
  case (entity1, tuples) => (entity1, tuples.map(_._2))
}

db.run(q.result)

但我在编译时收到此错误:

Error:(19, 35) No matching Shape found.
Slick does not know how to map the given types.
Possible causes: T in Table[T] does not match your * projection,
 you use an unsupported type in a Query (e.g. scala List),
 or you forgot to import a driver api into scope.
  Required level: slick.lifted.FlatShapeLevel
     Source type: (my.namespace.models.entity1Table, slick.lifted.Query[my.namespace.models.entity2Table,my.namespace.models.Entity2,[+A]Seq[A]])
   Unpacked type: T
     Packed type: G
    } yield (e1, e2)).groupBy(_._1) map {

我怀疑它不能映射entity1Table和entity2Table。

如何解决该错误?

1 个答案:

答案 0 :(得分:0)

根据Slick doc中的指定, try { int choice = 1; NewSessionBeanRemote libraryBean = (NewSessionBeanRemote)ctx.lookup("NewSessionBean/remote"); 当前不支持执行嵌套类型为groupBy的嵌套查询:

  

中间查询(即,查询以groupBy()结尾,但没有   聚合函数)包含查询类型的嵌套值。这些会   执行查询时变成嵌套的集合,而不是   目前支持。因此,有必要将   通过汇总查询的值(或单个查询)立即嵌套查询   列)

换句话说,您的Slick Query查询必须与一个等效于SQL的groupBycount()等的聚合函数结合使用。例如,以下查询等效于{ {1}}可以工作:

sum()