Slick:两个查询,一个事务

时间:2017-09-21 14:21:03

标签: scala transactions slick

我们说我有两张桌子:

people:

id: long | uuid: UUID     | name: String

----

cars

id: long | owner_id: long | name: String

其中ownerpeople.id的外键。

我有一个查询,按照所有者的uuid选择所有车主(仅限API设计)。

问题是:如何在一个必须通过其people.iduuid)然后SELECT id from people where uuid = ?获取SELECT * from cars where owner_id = id的交易中执行以下查询?< / p>

当然,我最初可以从id的{​​{1}}表中获取people,例如

uuid

然后运行另一个查询以val ownerId = db run people.filter(_.uuid === uuid.bind).map(_.id).result.head 选择汽车:

owner_id

但这不会发生在一次交易中。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

光滑动作有一种transactionally方法。你应该使用:

import slick.driver.PostgresDriver.api._  // for example

val query = for {
  p <- peoples.filter(_.uuid === "some-id")
  c <- cars.filter(_.owner_id === p.uuid)
} yield (p, c)

val action = query.result
val transactionalAction = action.transactionally // will be executed 
                                                 // in single transaction

// Ungrouped result
// TODO: You can group on db side by your query or 
// on client side using groupBy from collection API
val result:Future[Seq[(People, Cars)]] = db.run(transactionalAction)

答案 1 :(得分:0)

我说:

val groupByQuery =  cars.join(people)
 .on (_.owner_id === _.id)
 .map{
  case (car, owner) => (owner.uuid, car)
 }
.groupBy(_._1)

db.run(groupByQuery)