Ecto association with a condition

白昼怎懂夜的黑 提交于 2019-12-09 08:54:08

问题


Let's say I have two models, Post and Comment and the comment model can be 1 out of 2 types, normal and fancy which is defined by the column type in the comments table.

Now I want to add 2 associations on my Post model, where one refers to fancy comments and one to normal ones, how would I do it? So I want something like this:

has_many :fancy_comments, MyApp.Comment, where: [type: 0]
has_many :normal_comments, MyApp.Comment, where: [type: 1]

回答1:


This is not available in Ecto, there is a lengthy discussion about it on this GitHub issue.

You could use a composable query for this:

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

You can then use has_many :comments, MyApp.Comment and query based on that:

assoc(post, :comments) |> Comment.fancy() |> Repo.all()

Here is a blog post about composable queries.

You can also use a preload with a query:

fancy_query = from(c in Comments, where: type == 0)
Repo.preload(post, comments: fancy_query)


来源:https://stackoverflow.com/questions/33294328/ecto-association-with-a-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!