Slick 3 composite list insert in transaction

2019-05-21 00:33发布

问题:

I need to insert next case classes in transaction with saving ids relation:

case class A (id: Long, bList: List[B])
case class B (id: Long, aId: cList: List[C])
case class C (id: Long, bId: Long)

I know that its easy to save entity with one list inside:

def saveAWithBList(aTableObject: A): Future[Long] = {

  val saveQuery = (for {
     savedAId <- (aTable returning table.map(_.id)) += aTableObject
     savedBRows <- bTable ++= aTableObject.bList.map(_.copy(aId = savedAId))
  } yield savedAId).transactionally

  database.run(saveQuery)
}

But I didn't find solution to return bList element id for correct cList elements saving. I need something like this and I know that it doesn't work:

def saveAWithBListWithCList(aTableObject: A): Future[Long] = {

  val saveQuery = (for {
     savedAId <- (aTable returning aTable.map(_.id)) += aTableObject
     _ <- aTableObject.bList.map { bObject =>
            val savedBId = (bTable returning bTable.map(_.id)) += bObject.copy(_.aId = savedAId)
            cTable ++= bObject.cList.map(_.copy(bId = savedBId))
          }
  } yield savedAId).transactionally

  database.run(saveQuery)
}

Could you please help me with it?

回答1:

Next solution works fine:

  def saveAWithBListWithCList(aTableObject: A): Future[Long] = {

    val saveQuery = (for {
      savedAId <- (aTable returning aTable.map(_.id)) += aTableObject
      _ <- DBIO.sequence(aTableObject.bList.map { bObject =>
        ((bTable returning bTable.map(_.id)) += bObject.copy(aId = savedAId)).flatMap { bIdAction =>
          cTable ++= bObject.cList.map(_.copy(bId = bIdAction.result))
        }
      })
    } yield savedAId).transactionally

    database.run(saveQuery)
  }