Ecto:如何使用不同的随机数更新所有记录

Tab*_*Key 2 postgresql elixir ecto

我在 postgresql 中有一个表,我想用随机数更新所有记录的“points”列的值。在其他语言中,我们可以循环所有数据库记录,但我如何使用 ecto 来做到这一点?我试过这个:

 Repo.all(from u in User, update: User.changeset(u, %{points: :rand.uniform(100)}))
Run Code Online (Sandbox Code Playgroud)

但它输出以下错误:

== Compilation error in file lib/hello_remote/user.ex ==
** (Ecto.Query.CompileError) malformed update `User.changeset(u, %{points: :rand.uniform(100)})` in query expression, expected a keyword list with set/push/pop as keys with field-value pairs as values
expanding macro: Ecto.Query.update/3
lib/hello_remote/user.ex:30: HelloRemote.User.update_points/0
expanding macro: Ecto.Query.from/2
lib/hello_remote/user.ex:30: HelloRemote.User.update_points/0
(elixir 1.10.4) lib/kernel/parallel_compiler.ex:304: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/7
Run Code Online (Sandbox Code Playgroud)

我也尝试过这个:

from(u in User)
|> Repo.update_all(set: [points: Enum.random(0..100)])
Run Code Online (Sandbox Code Playgroud)

但它会用相同的值更新所有记录

pot*_*bas 8

您可以将fragment/1update_all/3结合使用,调用PostgreSQL函数来计算随机值,例如:

update(User, set: [points: fragment("floor(random()*100)")])
|> Repo.update_all([])
Run Code Online (Sandbox Code Playgroud)