如何解决如何使用 Doobie 插入链接对象
我需要在数据库中插入一个实体类型的对象
case class Entity(id: Long,name: String)
case class OtherEntity(id: Long,entity_id: Long,info: String)
case class AnotherEntity(other_entity_id: Long,data: String)
如果我在某处收到大约输入,我该怎么做
{
"name": "string","data": [
{
"info": "string","data": [
{
"data": "string"
}
]
}
]
}
主要问题是我想不出 doobie.ConnectioIO 的模拟 foreach。
sql"insert into entity (name) values('name')"
.update.withUniqueGeneratedKeys[Long]("id")
.flatmap(entityId =>
sql"insert into other_entity (entity_id,info) values ($entityId,'info')"
.update.withUniqueGeneratedKeys[Long]("id")
).flatmap(otherEntityId =>
sql"insert into another_entity (other_entity_id,data) values ($otherEntityId,'data')"
.update.run
)
但这仅适用于一对一关系。 感谢您的帮助。
解决方法
您可以将同一个外键的多个插入链接在一起。 IE。如果每个“名称”都有 List
个“信息”,则可以遍历该列表以返回 ConnectionIO[List[_]]
。如果您使用 ConnectionIO[Unit]
,或者只是一个 traverse_
。
import doobie.implicits._
import cats.implicits._
sql"insert into entity (name) values('name')"
.update.withUniqueGeneratedKeys[Long]("id")
.flatMap{ entityId =>
val infos: List[String] = ???
infos.traverse_{ info =>
sql"insert into other_entity (entity_id,info) values ($entityId,$info)"
.update.withUniqueGeneratedKeys[Long]("id")
.flatMap{ otherEntityId =>
val datas: List[String] = ???
datas.traverse_{ data =>
sql"insert into another_entity (other_entity_id,data) values ($otherEntityId,$data)"
.update.run
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。