假设我有两个 Ecto 模型(以及它们的迁移):
schema "projects" do
field :name, :string
belongs_to :client, MyApp.Client
timestamps
end
create table(:projects) do
add :name, :string
add :client_id, references(:clients)
timestamps
end
schema "clients" do
field :name, :string
has_many :projects, MyApp.Project
timestamps
end
create table(:clients) do
add :name, :string
timestamps
end
如果我查询了一个项目模型,例如。
project = Repo.get!(Project, proj.id)
正如预期的那样,我无法访问project.client.id
,因为我没有preload
在查询中使用 a 。
每当我尝试访问project.client_id
它时,它都会返回 nil。当然,我应该能够访问外键 ID 本身吗?
希望下面的代码能更好地说明:
client = Repo.insert!(%Client{name: "Test Client"})
proj = Repo.insert!(%Project{name: "Test Project 1", client: client})
project = Repo.get!(Project, proj.id)
assert project.client_id != nil
# ^ This always fails because project.client_id is nil