首页 > 解决方案 > 如何在 Ecto 迁移的执行语句中插入 Elixir 列表?

问题描述

如何执行此迁移:

types = ["a", "b", "c"]
execute "UPDATE table SET type='d' WHERE type in #{types}" 

通常,您会执行以下操作:

execute "UPDATE table SET type='d' WHERE type in ('a', 'b', 'c')"

但是如果类型来自一个可变长度的列表呢?

标签: elixirecto

解决方案


这是一种(可能是坏的)方法:

types = ["a", "b", "c"]
execute "UPDATE table SET type='d' WHERE type in ('#{Enum.join(types, "', '")}')"

这只是构建字符串。可能有更好的方法,涉及将函数传递给execute,就像这样(来自文档):

execute(fn -> repo().query!("select 'Anonymous function query …';", [], [log: :info]) end)

https://hexdocs.pm/ecto_sql/Ecto.Migration.html#execute/1

这看起来像:

execute(fn -> repo().query!("update table set type='d' where type = any($1)", [types]) end)

推荐阅读