【问题标题】:How to use results of one slick query in another with computation in between如何在另一个中使用一个光滑查询的结果并在两者之间进行计算
【发布时间】:2018-07-27 06:19:34
【问题描述】:

我有一个数据库表 InventoryLotUsage,其中包含列 id、inventoryLotId 和 date。我想删除一个 InventoryLot,但在执行此操作之前,我需要根据日期和其他一些条件更新具有外键 inventoryLotId 的 InventoryLotUsage 行。
我的问题是如何使用 monadic join 查询数据,对其进行一些计算并使用这些计算的结果在 Slick 的一个事务中运行更新?

我试图获得这样的一系列行

for {
      il <- InventoryLot.filter(_.id === id)
      lotUsage <- InventoryLotUsage.filter(_.inventoryLotId === id).result
      groupedUsage = lotUsage.groupBy(_.date)
      ...
}

我的 IDE 建议 lotUsage 将是一个 Seq[InventoryLotUsageRows],但是在编译时由于 .result 而出现类型错误。

type mismatch;
 found   : slick.dbio.DBIOAction[FacilityProductRepository.this.InventoryLot,slick.dbio.NoStream,slick.dbio.Effect.Read with slick.dbio.Effect.Read with slick.dbio.Effect.Read]
 required: slick.lifted.Query[?,?,?]
      lotUsage <- InventoryLotUsage.filter(_.inventoryLotId === id).result

不使用 .result 它的类型是 InventoryLotUsage 表。如何将查询转换为可用于计算的内容?

【问题讨论】:

  • 我想你忘记了il &lt;-线上的.result

标签: scala slick


【解决方案1】:

您需要撰写DBIOActions 以存档所需的结果。例如:

加载您需要的所有数据

val loadStaffAction = (for {
   il <- InventoryLot.filter(_.id === id)
   lotUsage <- InventoryLotUsage.filter(_.inventoryLotId === id)
} yield (il, lotUsage)).result

然后您可以在loadStaffAction 上使用map/flatMap 来创建基于计算的更新语句。您也可以在此处使用 for-comprehensions。

val updateAction = loadStaffAction.map { result =>
  // creating update statements based on some computations and conditions
  DBIO.seq(
    InventoryLotUsage.filter(_.id === inventory1.id).map(_.name).update("new value"),
    InventoryLotUsage.filter(_.id === inventory2.id).map(_.name).update("another value"),
  );
}

之后,您可以在一个事务中运行所有查询

db.run(updateAction.transactionally)

【讨论】:

    猜你喜欢
    • 2010-10-31
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多