Ecto 架构字段名称可以与列名称不同吗?

Ben*_*tes 1 elixir ecto

我有一个旧数据库,我正试图将其引入 Ecto。其中有一个orders表,其中有一order_status_id列。 order_status_id映射到遗留系统中的一组常量。

我想让MyApp.Order结构包含一个order_status字段,它有一个自定义类型,可以将整数 ID 转换为有意义的原子。我有自定义类型工作,但我无法弄清楚如何将名为的字段映射order_status到名为order_status_id.

遗留系统仍然在线并使用数据库,因此更改数据库架构不是一种选择。有没有办法让这个工作?

Eve*_*ett 7

我不确定第一次问这个问题时是否有可能,但现在有可能(Elixir 1.5)。请参阅https://hexdocs.pm/ecto/Ecto.Schema.html 特别是@field_source_mapper:source选项。该:source选项非常简单——只需将其包含在您的schema定义中,如下所示:

  schema "orders" do

    field :foo, :string, [source: :legacy_foo_db_column]
    field :status, :integer, [source: :order_status]

  end
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,现有的数据库表有名为“legacy_foo_db_column”和“order_status”的列,但在 Elixir 应用程序内部,架构和变更集等将使用名为“foo”和“status”的属性