Ecto模式字段名称可以与列名称不同吗? [英] Can the Ecto schema field name different from column name?

查看:68
本文介绍了Ecto模式字段名称可以与列名称不同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got a legacy database that I'm trying to pull into Ecto. In it there's an orders table which has an order_status_id column. order_status_id maps to a set of constants in the legacy system.

我想拥有 MyApp.Order 结构包含一个 order_status 字段,该字段具有将整数ID转换为有意义的原子的自定义类型。我已经使用了自定义类型,但是我不知道如何将名为 order_status 的字段映射到名为 order_status_id

I'd like to have the MyApp.Order struct contain an order_status field, which has a custom type that converts the integer IDs to meaningful atoms. I've got the custom type working, but I can't figure out how to map a field named order_status to a column named order_status_id.

旧版系统仍然在线并且正在使用数据库,因此不能更改数据库模式。有什么办法可以解决这个问题?

The legacy system is still online and using the database, so changing the DB schema is not an option. Is there any way to get this working?

推荐答案

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

I'm not sure if it was possible when the question was first asked, but it is possible now (Elixir 1.5). See https://hexdocs.pm/ecto/Ecto.Schema.html In particular the @field_source_mapper and :source options. The :source option is pretty easy -- just include it in your schema definition something like this:

  schema "orders" do

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

  end

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

In the above example, the existing database table has columns named "legacy_foo_db_column" and "order_status", but internally in the Elixir app, the schema and changeset etc. will use attributes named "foo" and "status"

这篇关于Ecto模式字段名称可以与列名称不同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆