【问题标题】:How to insert a linked object using Doobie如何使用 Doobie 插入链接对象
【发布时间】:2021-07-21 16:26:14
【问题描述】:

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

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
)

但这仅适用于一对一的关系。 感谢您的帮助。

【问题讨论】:

    标签: scala doobie


    【解决方案1】:

    您可以将同一个外键的多个插入链接在一起。 IE。如果每个“名称”都有 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
              }
            }
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2021-08-19
      • 1970-01-01
      • 2019-10-13
      • 2010-09-14
      • 1970-01-01
      • 2013-11-24
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多