Scala+Slick 3:将一个查询的结果插入到另一个表中 [英] Scala+Slick 3: Inserting the result of one query into another table
问题描述
这个问题是关于 slick 3.0 或 3.1(我对此很灵活)
This question is about slick 3.0 or 3.1 (I am flexible about that)
我有一个中间查询,我使用 map
、for
等处理该查询以获得我想要的结果.最后我有一个
I have an intermediate query which I process with map
, for
, etc. to obtain the result I want. In the end I have a
val foo: DBIOAction[Seq[MySchema.Bar], NoStream, Effect.Read]
现在我有一个 val bar: TableQuery[MySchema.Bar]
并且我想在其中插入 foo.
Now I have a val bar: TableQuery[MySchema.Bar]
and I want to insert foo in to it.
如果 foo 是 Seq
我可以简单地做 bar ++= foo
,但它不是.
If foo would be a Seq
I could simply do bar ++= foo
, but it is not.
我发现的唯一方法是通过等待来实现结果.像这样
The only way I found is to materialize the result by awaiting it. Like this
val query = (bar ++= Await.result(db.run(foo), Duration.Inf))
显然query
需要在某个时候使用db.run
运行.但现在我有两个数据库运行.一次性完成所有内容不是更好吗?
Obviously query
needs to be run at some point with db.run
. But now I have two DB-runs. Wouldn't it be better to have everything in a single run?
有没有更好的方法来做到这一点?
推荐答案
DBIOAction
有 map
/flatMap
函数,所以你可以写点东西喜欢
DBIOAction
has map
/flatMap
functions, so you can write something like
val insertAction = foo.flatMap(bar ++= _)
insertAction
将是 DBIOAction[Int, NoStream, Effect.Write]
或类似的类型(我不完全确定 Int
和效果),然后您可以使用 db.run
将它作为任何 DBIOAction
在数据库上运行;然后你得到的是整个查询和插入结果的未来.
The insertAction
will be of type DBIOAction[Int, NoStream, Effect.Write]
or something like that (I'm not entirely sure about Int
and the effect), then you can run it on the DB as any DBIOAction
using db.run
; what you then get is a future of the overall query and insert result.
这篇关于Scala+Slick 3:将一个查询的结果插入到另一个表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!