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

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

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

但它输出以下错误:

== 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

我也试过这个:

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

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

最佳答案

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

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

https://stackoverflow.com/questions/64242752/

相关文章:

swiftui - 编辑 : How we can alignment Image with Ima

terraform - 如何定义 "azurerm_resource_group_template_

reactjs - 如何触发事件 React 测试库

json - 使用 Mule 中的 Dataweave 将定界文件转换为 JSON 格式

java - 无效的正则表达式 : Dangling meta character "*"

ruby-on-rails - 使用 Cloudinary 和 Active Storage 时如何

unity3d - 如何将 Input.GetAxis ("Mouse X") 或 Input.Ge

python - 无法用pip安装pycuda

github - 使用 SonarQube(社区版)装饰 GitHub 中的拉取请求

C - 如何通过函数增加指向字符串的指针?