在ecto中没有belongs_to的has_one

时间:2017-05-28 15:15:19

标签: elixir ecto

想象一下,我有两个架构:UserJob,其中JobFirefighterTeacherPolice Officer等等。

每个User只能有一个Jobhas_one),但每个Job都会有无限数量User,我真的甚至不关心能否从给定的User找到Job

我无法理解必须在has_one上定义User,而 belongs_toJob能够预加载关联。我知道我可以使用many_to_many表将其定义为UserClass,但这似乎有点过分了。我在努力绕过我的选择。

1 个答案:

答案 0 :(得分:0)

  

每个用户只能有一个Job(has_one),但每个Job都有无限数量的User,我甚至不关心能否从给定的Job中找到User。

我认为这就是你要做的。每个用户belongs_to一个职位和每个职位has_many用户。

用户:

在迁移中:

def change do
  create table(:users) do
    add :job_id, references(:jobs, on_delete: :nothing)
  end

  create index(:users, [:job_id])
end
模特中的

defmodule User do
  schema "users" do
    belongs_to :job, Job
  end
end

工作:

模特中的

defmodule Job do
  schema "jobs" do
    has_many :users, User
  end
end