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