【问题标题】:Reference a composite key in a `belongs_to` association in Ecto?在 Ecto 的“belongs_to”关联中引用复合键?
【发布时间】:2020-05-07 10:20:17
【问题描述】:

我正在尝试将一个实体 A 建模为仅附加,另一个子实体引用第一个实体。所以 A 的结构类似于(按inserted_at DESC 排序):

|  id  |  version  |  column | inserted_at |
|------|-----------+---------|-------------|
|   5  |     2     |  "baz"  | 2020-04-20  |
|   3  |     2     |  "zoot" | 2020-04-20  |
|   3  |     1     |  "bar " | 2020-04-18  |
|   5  |     1     |  "foo"  | 2020-04-10  |

(id, version) 构成 A 的主键((id, inserted_at) 也可以,但开发人员认为版本号更具可读性)。

现在 B 属于 A,每个 B 将对应一对 (id, version) A。所以类似于:

|  id  |  a_id | a_version |  column | inserted_at |
|------|-------+-----------+---------+-------------|
|   4  |   5   |    2      |  "pigs" | 2020-05-05  |
|   3  |   5   |    2      |  "goats"| 2020-05-03  |
|   2  |   5   |    1      |  "rams" | 2020-05-02  |
|   1  |   3   |    1      |  "bears"| 2020-04-18  |

我的问题是,如何使用 Ecto Schemas 对这些进行建模?我想我从阅读文档中知道 A 架构是什么样的,除了 has_many

defmodule MyASchema do 
  use Ecto.Schema

  @primary_key false
  schema "table_a" do
    field :id, :id, primary_key: true
    field :version, :integer, primary_key: true
    field :column, :string
    field :inserted_at, :utc_datetime
    has_many :bs, MyBSchema  # what goes here for :foreign_key?
  end
end

但是 B 模式(尤其是 belongs_to)对我来说不太清楚:

defmodule MyBSchema do 
  use Ecto.Schema

  @primary_key
  schema "table_b" do
    field :id, :id, primary_key: true
    field :column, :string
    field :inserted_at, :utc_datetime

    # how does belongs_to work here? would it be 
    #
    # belongs_to :a, MyASchema, primary_key: [:id, :version]
    #
    # or 
    #
    # belongs_to :a, MyASchema, define_key: false
    # field :a_id, :id
    # field :a_version, :integer
    #
    # ? If so, how could I query such that the :a field of the
    # struct is populated?
  end
end

很高兴进一步澄清,感谢阅读+任何帮助????

【问题讨论】:

    标签: elixir ecto phoenix


    【解决方案1】:

    根据Elixir forum,Ecto 在使用关联时不支持复合外键。

    一种解决方案是添加一个“常规”唯一主键(例如,自动递增整数或 UUID)并将引用作为该 ID 的基础。有时您在使用数据库抽象层时会感到安慰,因为当数据库具有简单的单列主键(即不是组合)时,关系更容易定义。

    如果无法更改数据库架构,则需要手动解析代码中的关联。您可能需要设置多个事务,如this post 所述。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多