很明显如何预先加载Ecto 1-2级别的关联,例如帖子和评论。
我有一个Address
,Address
属于Street
,Street
属于City
,City
属于地区,Region
属于Country
鉴于Address
:
addr = Repo.get(Address, 123)
|> Repo.preload(street: ?????)
我怎么预先加载到Country
:
IO.puts("the name of country: #{addr.street.city.region.country.name}")
?
根据the docs Repo.preload/3
类似于Ecto.Query.preload/3
,你可以将预先加载的嵌套列表传递给它们。
Repo.preload/3
:addr =
Address
|> Repo.get(123)
|> Repo.preload(street: [city: [region: :country]])
IO.inspect(addr.street.city.region.country)
Ecto.Query.preload/3
:addr =
Address
|> Ecto.Query.where(id: 123)
|> Ecto.Query.preload(street: [city: [region: :country]])
|> Repo.one()
IO.inspect(addr.street.city.region.country)