问题
我有一个 files
表,还有许多其他表可以创建一对一关联,例如users
可能有 avatar
和 posts
可能有 photo
.
一个可能的解决方案
一个可能的解决方案是创建 users_files
和 posts_files
表和使用 has_one :through
.然而,这看起来太过分了。
理想的解决方案
理想的解决方案是定义这样的表
users
- avatar_id
posts
- photo_id
并有 with:
has_one
中的参数所以架构看起来像这样schema "users" do
has_one :avatar, MyApp.FileDb, with: :avatar_id, foreign_key: :id #id is default
end
schema "posts" do
has_one :photo, MyApp.FileDb, with: :photo_id, foreign_key: :id
end
这样你就不需要定义 belongs_to
在 files
.已经有类似的机制了吗?在 Phoenix 处理这个问题的标准方法是什么?
最佳答案
您无法避免没有belongs_to,因为那是定义外键的地方。您有两种选择:
关于elixir - has_one 在 ecto/phoenix/elixir 中没有belongs_to,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32670161/