如何使用Postgres使用Ecto存储数组

Jos*_*itt 38 postgresql ecto phoenix-framework

我想使用Postgres使用Ecto存储一个浮点值数组.我正在使用Ecto与Phoenix Framework和Elixir.

我如何为此定义模型和迁移?

我没有尝试太多,除了搜索网络,没有找到任何有用的东西:-(

我尝试使用如下模式定义模型:

  schema "my_model" do
    field :my_array, :array

    timestamps
  end
Run Code Online (Sandbox Code Playgroud)

出现错误"无效或未知类型:字段数组:my_array"

Jos*_*itt 60

我在这里找到了Ecto.Schema的基本类型列表中的答案:

Ecto.Schema

答案是定义这样的类型:

  schema "my_model" do
    field :my_array, {:array, :float}

    timestamps
  end
Run Code Online (Sandbox Code Playgroud)

  • 这是一个生成器示例:`mix phx.gen.schema Blog.Post blog_posts tags:array:string` (8认同)
  • 谢谢,你会如何编写迁移? (7认同)
  • @sash 中的示例使用相关行 `add :tags, {:array, :string}` 生成迁移 (3认同)

Bar*_*ira 28

正如您所写,使用Ecto.Schema中的数组类型

在模型中:

schema "my_model" do
  field :my_array, {:array, inner_type}
end
Run Code Online (Sandbox Code Playgroud)

@neildaemond迁移:

alter table(:my_models) do
  add :my_array, {:array, inner_type}
end
Run Code Online (Sandbox Code Playgroud)

替换inner_type为其中一种有效类型,例如:string.

您也可以使用map类型执行相同的操作:

schema "my_model" do
  field :my_map, {:map, inner_type}
end
Run Code Online (Sandbox Code Playgroud)

  • 知道如何正确构建一个表单,让某人输入这个数组或映射的元素吗? (2认同)