scala - 如何通过一个请求将各种表中的数据放入单独的列表中
问题描述
例如,我有一些实体。每个实体都有一些属性。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]
?
解决方案
Scala 中的列表是同构的,这意味着编译器将尝试找到列表中所有对象类型的上限。
Entity
对于您的情况,和的上限EntityAttribute
是Product
。
保留原始类型可以做的只是返回一个包含两个列表的元组:List[Entity]
和List[EntityAttribute]
.
} yield (entitites, attributes)).transact(xa)
然后,您可以仅通过对元组进行模式匹配来检索列表:
result.map {
case (entities, attributes) => /* do something */
}
推荐阅读
- angular - 通过 ngx-cookieconsent 删除 cookie
- javascript - 我如何将不同变量的多个不同值从 popup.js 发送到 inject.js 以便可以在 inject.js 脚本中使用?
- android - 错误:包 android.view 不存在
- javascript - 调用插件方法在 jQuery 中动态添加元素到 DOM
- python - 使用 Kivy/Buildozer 后应用程序无法运行
- wpf - 使用 TextBlock 扩展的 WPF TextBlock 绑定到 ViewModel 不起作用
- python - 强制覆盖 PySimpleGUI 窗口
- c - 从 C 中的标准输入中准确读取 N 个字节
- python - 试图了解如何在 Python 中使用多线程 websocket,但似乎被一个线程卡住了
- laravel - Subscriptions 和 subscription_item 数据库使用 Stripe 结帐为空