加载带有标题的子节

时间:2019-09-10 01:44:09

标签: postgresql elixir ecto

我正在做一些left_joins,试图预加载一些嵌套的关联。我有sections,有sub_sections,并且我想获取所有具有标题的sub_sections(与没有标题的sub_sections相对)。当我添加这一行时,整个查询返回nil,但是当我删除它时,我得到了所有内容(包括没有标题的sub_sections)。 where: not is_nil(sub2.title)

我很难在这里找到我做错了什么?我觉得我应该得到这个结果。

任何帮助将不胜感激。谢谢!

from a in Article,
  left_join: s in assoc(a, :sections),
  left_join: d in assoc(s, :definitions),
  left_join: sub in assoc(d, :sub_sections),
  left_join: sub2 in assoc(sub, :sub_sections),
  where: a.id == ^id,
  where: not is_nil(sub2.title),
  preload: [sections: {s, [definitions: {d, [sub_sections: {sub, sub_sections: sub2}]}]}]```

1 个答案:

答案 0 :(得分:1)

您应该将条件not is_nil(sub2.title)应用于相应的join,而不是整个查询。像下面这样应该可以工作。

subs = from sub in SubSection, where: not is_nil(sub.title)

from a in Article,
  left_join: s in assoc(a, :sections),
  left_join: d in assoc(s, :definitions),
  left_join: sub in assoc(d, :sub_sections),
  left_join: sub2 in ^subs, on: sub2.parent == sub.id,
  where: a.id == ^id,
  preload: [sections: {
    s, [definitions:
     {d, [sub_sections: {sub, sub_sections: sub2}]}]}]