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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33065318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:04:07  来源:igfitidea点击:

How to store array with Ecto using Postgres

postgresqlphoenix-frameworkecto

提问by Josh Petitt

I would like to store an array of floating point values with Ecto using Postgres. I'm using Ecto with the Phoenix Framework and Elixir.

我想使用 Postgres 使用 Ecto 存储浮点值数组。我正在使用带有 Phoenix 框架和 Elixir 的 Ecto。

How would I define my model and migration for this?

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

I haven't tried much, except searching the web, which didn't find anything useful :-(

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

I did try defining a model with a schema like this:

我确实尝试使用这样的模式定义模型:

  schema "my_model" do
    field :my_array, :array

    timestamps
  end

which gave an error "invalid or unknown type :array for field :my_array"

这给出了错误“无效或未知类型:字段的数组:my_array”

回答by Josh Petitt

I found the answer in the list of primitive types for Ecto.Schema here:

我在 Ecto.Schema 的原始类型列表中找到了答案:

Ecto.Schema

外链模式

The answer is to define the type like this:

答案是这样定义类型:

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

    timestamps
  end

回答by Bartek Skwira

As Josh wrote use the array type from Ecto.Schema

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

In the model:

在模型中:

schema "my_model" do
  field :my_array, {:array, inner_type}
end

@neildaemond Migration:

@neildaemond 迁移:

alter table(:my_models) do
  add :my_array, {:array, inner_type}
end

Replace inner_typewith one of the valid types, such as :string.

替换inner_type为有效类型之一,例如:string.

You can also do the same thing with a maptype:

你也可以用一个map类型做同样的事情:

schema "my_model" do
  field :my_map, {:map, inner_type}
end