0
我有三個模型Table1
,Table2
和Table1to2
。 Table1to2
從表1聯接表,表2,與Table 1和表2是架構:在ecto assoc加入表中添加where子句
schema "table1" do
many_to_many :table2, Table2, join_through: Table1to2
end
schema "table2" do
many_to_many :table1, Table1, join_through: Table1to2
end
關鍵的一點是,我的連接表,Table1to2
有一欄/場,我需要對查詢。從本質上講,我希望做這樣的事情:
Repo.get!(Table1, id) |> Repo.preload(table2: (from j in Table1to2, where: [main: true]))
這可以理解不起作用,因爲沒有直接定義的關聯從表1至Table1to2。然而,這樣做:
Repo.get!(Table1, id) |> Repo.preload(table2: (from j in Table2, where: [main: true]))
結果在此查詢:
from p0 in Table1,
join: u in Table1to2,
on: u.table1_id == p0.id,
join: p1 in Table2,
on: u.table2_id == p1.id,
where: p1.main == true, #should be u.main == true
where: p0.id == ^"2",
select: p0,
preload: [table_2: p1]
沒錯,那就是我現在正在做的事情。如果有一種方法可以在沒有明確查詢的情況下執行此操作,那將是非常好的,因爲當我必須預加載/鏈接其他查詢時,它是PITA。 Ecto也支持自定義的HABTM模型,這讓我覺得應該有一種方法可以乾淨地做到這一點。 – Secret