与条件的依存关系

问题描述 投票:14回答:2

假设我有两个模型PostComment,并且注释模型可以是normalfancy这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]
elixir phoenix-framework ecto
2个回答
17
投票

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)

© www.soinside.com 2019 - 2024. All rights reserved.