首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Doobie插入链接对象

如何使用Doobie插入链接对象
EN

Stack Overflow用户
提问于 2021-04-28 18:06:21
回答 1查看 51关注 0票数 0

我需要在数据库中插入一个Entity类型的对象

代码语言:javascript
复制
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)

如果我在某处收到输入,我该怎么做?

代码语言:javascript
复制
{
    "name": "string",
    "data": [
        {
            "info": "string",
            "data": [
                {
                    "data": "string"
                }       
            ]
        }
    ]
}

主要的问题是我不能为doobie.ConnectioIO想出一个模拟的foreach。

代码语言:javascript
复制
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
)

但这只适用于一对一的关系。谢谢你的帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-28 19:04:54

您可以将同一外键的多个插入链接在一起。也就是说,如果你对每个“名字”都有一个"infos“的List,你可以遍历这个列表,返回一个ConnectionIO[List[_]]。或者,如果您使用traverse_,则只需要一个ConnectionIO[Unit]

代码语言:javascript
复制
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
          }
        }
    }
  }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67298111

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档