假设我有两个模型Post
和Comment
,并且注释模型可以是normal
和fancy
这2种类型中的1种,它们由type
表中的comments
列定义。
现在,我想在我的Post
模型上添加2个关联,其中1个引用花哨的注释,而1个引用普通的注释,我该怎么做?所以我想要这样的东西:
has_many :fancy_comments, MyApp.Comment, where: [type: 0]
has_many :normal_comments, MyApp.Comment, where: [type: 1]
Ecto中没有此功能,this GitHub issue上对此进行了冗长的讨论。
您可以为此使用可组合查询:
defmodule MyApp.Comment do
...schema, etc.
def fancy(query) do
from c in query,
where: type == 0
end
def normal(query) do
from c in query,
where: type == 1
end
end
然后您可以使用has_many :comments, MyApp.Comment
并根据其进行查询:
assoc(post, :comments) |> Comment.fancy() |> Repo.all()
这里是有关composable queries的博客文章。>>
您还可以在查询中使用预加载:
fancy_query = from(c in Comments, where: type == 0)
Repo.preload(post, comments: fancy_query)