从 table 获取外键的惯用方法

Idiomatic way to get foreign key from a table

假设我有一个 table "customers"。我想得到那个 table.

的外键

我们可以使用 model.__struct.__meta`

从模型中获取 table 名称

我们还可以通过加载所有模块从 table 获取模型名称,并获取与 table 名称

匹配的模型模式

我们是否可以从 table 中获取外键?

执行此操作的最佳方法是什么?

如果可能的话?

谢谢。

以下是查找模型中每个 belongs_to 关联的外键的方法:

schema "comments" do
  belongs_to :post, MyApp.Post
  belongs_to :user, MyApp.User
end
alias MyApp.Comment

for name <- Comment.__schema__(:associations),
    %Ecto.Association.BelongsTo{owner_key: owner_key} <- [Comment.__schema__(:association, name)] do
  IO.inspect owner_key
end

输出:

:post_id
:user_id

owner_key是当前table中的列名。还有 related_key 可用,它是相关 table.

中的列名