如何在 Ecto 迁移的执行语句中插入 Elixir 列表?
How to interpolate an Elixir list in an execute statement in Ecto migrations?
如何执行此迁移:
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')"
但是如果类型来自可变长度的列表怎么办?
这是一个(可能不好的)方法:
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()", [types]) end)
如何执行此迁移:
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')"
但是如果类型来自可变长度的列表怎么办?
这是一个(可能不好的)方法:
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()", [types]) end)