我有三个模型Table1
,Table2
和Table1to2
。 Table1to2
是Table1到Table2的连接表,Table1和Table2的模式为:
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]))
这是可行的,因为从Table1到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]
答案 0 :(得分:0)
您始终可以使用查询语法,例如您发布的结果查询,以满足您的需求。
query =
from t1 in Table1,
join: t12 in Table1to2, on: t12.table1_id == t1.id,
join: t2 in Table2, on: t12.table2_id == t2.id,
where: t12.main == :true and t1.id == ^table1_id,
preload: [table2: t1],
select: t1
result = Repo.one(query)