我需要在数据库中插入一个Entity类型的对象
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
)但这只适用于一对一的关系。谢谢你的帮助。
发布于 2021-04-28 19:04:54
您可以将同一外键的多个插入链接在一起。也就是说,如果你对每个“名字”都有一个"infos“的List,你可以遍历这个列表,返回一个ConnectionIO[List[_]]。或者,如果您使用traverse_,则只需要一个ConnectionIO[Unit]。
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
}
}
}
}https://stackoverflow.com/questions/67298111
复制相似问题