Scala 如何通过一个请求将不同表中的数据放入单独的列表中
例如,我有一些实体。每个实体都有一些属性。DB关注以下方面:Scala 如何通过一个请求将不同表中的数据放入单独的列表中,scala,doobie,Scala,Doobie,例如,我有一些实体。每个实体都有一些属性。DB关注以下方面: entity entity_attribute ╔════╦════════╗ ╔════╦════════════╦═══════════╗ ║ id ║ name ║ ║ id ║ entity_id ║ attribute ║ ╠════╬════════╣ ╠════╬════════════╬═══════════╣ ║ 1 ║ One ║
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)
如何修改doobie请求以将结果分成两个独立的
List[Entity]
和List[EntityAttribute]
?Scala中的列表是同构的,这意味着编译器将尝试查找列表中所有对象类型的上限
对于您的情况,实体
和实体属性
的上限是产品
要保留原始类型,只需返回一个包含两个列表的元组:List[Entity]
和List[EntityAttribute]
} yield (entitites, attributes)).transact(xa)
然后,您可以通过对元组进行模式匹配来检索列表:
result.map {
case (entities, attributes) => /* do something */
}
result.map {
case (entities, attributes) => /* do something */
}