我正在学习凤凰和ecto协会,但我偶然发现了一个在尝试预加载嵌套关联时似乎无法解决的问题。我有3个架构
提供
schema "offers" do
...
has_one :albumMariageSmall, Album, on_delete: :delete_all, on_replace: :delete
has_one :prewedding, Prewedding, on_delete: :delete_all,
on_replace: :delete
has_one :next_day, Prewedding, on_delete: :delete_all, on_replace: :delete
end
现在,Prewedding看起来像
schema "preweddings" do
...
has_one :album, Album, on_delete: :delete_all, on_replace: :delete
end
,相册看起来像
schema "albums" do
...
belongs_to :offer, Offer
belongs_to :prewedding, Prewedding
end
换句话说,一个优惠可以有一个专辑和两个Prewedding,Prewedding可以有一个专辑。
数据库方面,:preweddings通过offer_id引用商品,并且:albums通过offer_id引用商品,并通过prewedding_id引用预付款。
我无法加载任何已保存的商品:prewedding和:next_day在我检查时似乎指向同一行。
我正在尝试使用
预加载offer=Repo.one from(o in Offer, preload: [{:prewedding, [:album]},{:next_day, [:album]}], select: o, where: o.id==^id)
我认为我可以使用连接,但我很顽固,想要做预加载。
有人可以协助吗?
preweddings的迁移就是这个
add :included, :boolean, default: false, null: false
add :offer_id, references(:offers)
专辑
add :offer_id, references(:offers)
add :prewedding_id, references(:preweddings)
答案 0 :(得分:0)
默认情况下,使用has_one
时,外键是从当前表的名称推断出来的,例如: offers
- > offer_id
。由于您有两个has_one
并且您没有为其中任何一个指定自定义外键,因此两者都将使用offer_id
作为外键,因此将始终具有相同的值。您需要为两个has_one
指定正确的外键。例如,如果您的preweddings
表具有此迁移:
add :offer_prewedding_id, references(:offers)
add :offer_next_day_id, references(:offers)
你需要这样做:
has_one :prewedding, Prewedding, on_delete: :delete_all, on_replace: :delete, foreign_key: :offer_prewedding_id
has_one :next_day, Prewedding, on_delete: :delete_all, on_replace: :delete, foreign_key: :offer_next_day_id