首页 > 解决方案 > 如何通过一个请求将各种表中的数据放入单独的列表中

问题描述

例如,我有一些实体。每个实体都有一些属性。DB看起来是这样的:

 entity                entity_attribute
╔════╦════════╗       ╔════╦════════════╦═══════════╗
║ id ║ name   ║       ║ id ║ entity_id  ║ attribute ║
╠════╬════════╣       ╠════╬════════════╬═══════════╣
║ 1  ║  One   ║       ║ 1  ║ 1          ║ "aaa"     ║ 
║ 2  ║  Two   ║       ║ 2  ║ 1          ║ "bbb"     ║
║ 3  ║  Three ║       ║ 3  ║ 1          ║ "ccc"     ║
╚════╩════════╝       ║ 4  ║ 1          ║ "ddd"     ║
                      ║ 5  ║ 2          ║ "aa"      ║
                      ║ 6  ║ 2          ║ "bb"      ║
                      ╚════╩════════════╩═══════════╝

我的模型如下所示:

case class Entity(id: Long, name: String)

case class Entityattribute(id: Long, entityId: Long, attribute: String)

我正在尝试通过以下方式获取具有属性的实体(重要:不加入doobie

(for {
      entitites <- sql"select id, name from entity"query[Entity].to[List]
      attributes <- (sql"select id, entity_id, attribute from entity_attribute where " ++ 
                    Fragments.in(
                      fr"entity_id", 
                      NonEmptyList.fromListUnsafe(entities.map(_.id)))   //Unsafe, just example
                    ).query[EntityAttribute].to[List]
      } yield entitites ++ attributes).transact(xa)

结果是一个List[Product]

List(
  Entity(1, One),
  Entity(2, Two),
  Entity(3, Three),
  EntityAttribute(1,1,"aaa"),
  EntityAttribute(2,1,"bbb"),
  EntityAttribute(3,1,"ccc"),
  EntityAttribute(4,1,"ddd"),
  EntityAttribute(5,2,"aa"),
  EntityAttribute(6,2,"bb")
)

如何修改 doobie 请求以将结果分成两个单独List[Entity]的和List[EntityAttribute]

标签: scaladoobie

解决方案


Scala 中的列表是同构的,这意味着编译器将尝试找到列表中所有对象类型的上限。

Entity对于您的情况,和的上限EntityAttributeProduct

保留原始类型可以做的只是返回一个包含两个列表的元组:List[Entity]List[EntityAttribute].

} yield (entitites, attributes)).transact(xa)

然后,您可以仅通过对元组进行模式匹配来检索列表:

result.map {
   case (entities, attributes) => /* do something */
}

推荐阅读