Ecto 与某种情况的关联

2024-02-16

假设我有两个模型,Post and Comment评论模型可以是两种类型中的一种,normal and fancy由列定义type in the comments table.

现在我想在我的上添加 2 个关联Post模型,其中一个指的是花哨的评论,一个指的是普通的评论,我会怎么做?所以我想要这样的东西:

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

直到最近,Ecto 中还无法提供此功能。该问题的另一个答案提供了当前的详细信息。关于如何添加它进行了长时间的讨论这个 GitHub 问题 https://github.com/elixir-lang/ecto/issues/659.

在旧版本的 Ecto 中,您可以使用可组合查询来执行此操作:

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()

这是一篇关于可组合查询 http://blog.drewolson.org/composable-queries-ecto/.

您还可以在查询中使用预加载:

fancy_query = from(c in Comments, where: type == 0)
Repo.preload(post, comments: fancy_query)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Ecto 与某种情况的关联 的相关文章

随机推荐