从表中获取外键的惯用法

scr*_*ipt 0 elixir ecto

让我们假设我有一张桌子"customers".我想获得该表的外键.

我们可以使用model.__ struct .__ meta` 从模型中获取表名

我们还可以通过加载所有模块从表中获取模型名称,并使模型模式与表名匹配

这可能是我们从表中获取外键吗?

这样做的最佳方法是什么?

如果它可能在ecto?

谢谢.

Dog*_*ert 6

以下是如何belongs_to在模型中查找每个关联的外键:

schema "comments" do
  belongs_to :post, MyApp.Post
  belongs_to :user, MyApp.User
end
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

输出:

:post_id
:user_id
Run Code Online (Sandbox Code Playgroud)

owner_key是当前表中的列名称.还有related_key可用的是相关表中的列名.