Ecto与条件的关联

NoD*_*ame 14 elixir ecto phoenix-framework

比方说,我有两个型号,PostComment和评论模型可以是1出2种,normal并且fancy这是由列定义typecomments表.

现在我想在我的Post模型上添加2个关联,其中一个引用花哨的注释,一个引用正常注释,我该怎么做?所以我想要这样的东西:

has_many :fancy_comments, MyApp.Comment, where: [type: 0]
has_many :normal_comments, MyApp.Comment, where: [type: 1]
Run Code Online (Sandbox Code Playgroud)

Gaz*_*ler 17

这在Ecto中不可用,关于这个GitHub问题有一个冗长的讨论.

您可以使用可组合查询:

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
Run Code Online (Sandbox Code Playgroud)

然后has_many :comments, MyApp.Comment,您可以使用和查询:

assoc(post, :comments) |> Comment.fancy() |> Repo.all()
Run Code Online (Sandbox Code Playgroud)

这是一篇关于可组合查询的博客文章.

您还可以使用带有查询的预加载:

fancy_query = from(c in Comments, where: type == 0)
Repo.preload(post, comments: fancy_query)
Run Code Online (Sandbox Code Playgroud)


den*_*lin 6

条件关联现在可在Ectohttps ://hexdocs.pm/ecto/Ecto.Schema.html#has_many/3-filtering-associations

defmodule Post do
  use Ecto.Schema

  schema "posts" do
    has_many :public_comments, Comment, where: [public: true]
  end
end
Run Code Online (Sandbox Code Playgroud)